Torch is an open source framework used to build and train machine learning models. It was originally written in Lua and made it easy for researchers to experiment with deep learning. It provides tensors like NumPy arrays with GPU support, automatic differentiation and ready to use layers for neural networks.
Why to use Torch in Machine Learning?
- Enables rapid prototyping of deep learning models: Torch’s modular design makes it easy to build and test new neural network architectures. Researchers can combine layers, activation functions and loss functions quickly which speeds up experimentation.
- Supports GPU acceleration for faster training: Torch has built in support for CUDA so you can run heavy matrix operations on GPUs instead of CPUs. This significantly reduces training time for large models and big datasets.
- Highly extensible for researchers: Torch’s codebase is open source and modular so researchers can write custom layers, loss functions or optimizers. This makes it easy to test new algorithms or adapt existing ones to unique use cases.
- Has an active community that shares models and tools: Torch’s community contributed many pre trained models, libraries and tools which helped beginners and experts save time. These shared resources made it easier to learn, reproduce papers and build on others work.
Basic Functions of Torch
| Function | Description |
|---|---|
| torch.tensor() | Creates a tensor from data. |
| torch.zeros() | Creates a tensor filled with zeros. |
| torch.reshape() | Changes the shape of a tensor without changing its data. |
| torch.view() | Similar to reshape used to change tensor shape. |
| torch.sum() | Computes the sum of tensor elements along a dimension. |
torch.mean() | Computes the mean of tensor elements along a dimension. |
| torch.max() / min() | Returns the maximum or minimum value of the tensor. |
| torch.cat() | Concatenates tensors along a given dimension. |
| torch.stack() | Stacks tensors along a new dimension. |
| torch.save() | Saves a tensor to a file. |
| torch.load() | Loads a tensor from a file. |
How to install Torch
Step 1: Install Torch
!git clone https://github.com/torch/distro ~/torch --recursive
!cd ~/torch
!bash install-deps
!./install.sh
Step 2: Check for Installation
import torch
print(torch.__version__)
print(torch.cuda.is_available())
Output:
2.6.0+cu124
False
Let's take an Example
- This code trains a simple linear regression model using PyTorch to learn the relationship y = 2x + 1 from input data.
- It uses mean squared error as the loss and stochastic gradient descent (SGD) to update the model’s weight and bias.
- After training it prints the model’s predicted values for the input data.
import torch
import torch.nn as nn
import torch.optim as optim
X = torch.tensor([[1.0], [2.0], [3.0], [4.0]])
Y = torch.tensor([[3.0], [5.0], [7.0], [9.0]])
# Define simple linear model
model = nn.Linear(in_features=1, out_features=1)
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)
epochs = 1000
for epoch in range(epochs):
outputs = model(X)
loss = criterion(outputs, Y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (epoch+1) % 100 == 0:
print(f'Epoch [{epoch+1}/{epochs}], Loss: {loss.item():.4f}')
predicted = model(X).detach()
print("\nPredicted values:\n", predicted)
Output:

Torch vs PyTorch
Let us now compare Torch (Lua Version) with PyTorch (Python version):
| Feature | Torch | PyTorch |
|---|---|---|
| Language | Lua | Python |
| Dynamic Graphs | Yes, but less flexible | Yes, with strong Python integration |
| Ease of Use | More complex due to Lua syntax | Easy and intuitive for Python users |
| Community Support | Smaller, older community | Large and active community |
| Debugging | Harder (Lua ecosystem) | Easy (Python tools, interactive mode) |
| Extensibility | Good for research, but Lua-limited | Highly extensible with Python ecosystem |
| Ecosystem | Limited, Lua based libraries | Strong Python ecosystem (NumPy, SciPy) |
| Current Usage | Rarely used now | Widely used in research & production |
Applications
- Computer Vision: With Torch and PyTorch researchers build powerful models that can recognize objects in images, detect faces and segment scenes pixel by pixel. It’s widely used in self driving cars, security cameras and healthcare diagnostics.
- Natural Language Processing (NLP): Torch makes it simple to build models that understand and generate human language. You can create smart assistants that answer questions, translate text between languages or summarize long documents.
- Speech and Audio: Torch is used to train models that convert spoken words into text or generate human like speech from text. This powers virtual assistants, transcription tools and real time voice synthesis.
- Generative Models: With Torch you can build generative models that create new content from scratch like deepfake videos or artistic images. GANs (Generative Adversarial Networks) are also used for data augmentation in training.