Sprint Chase Technologies
  • Home
  • About
    • Why Choose Us
    • Contact Us
    • Team Members
    • Testimonials
  • Services
    • Web Development
    • Web Application Development
    • Mobile Application Development
    • Web Design
    • UI/UX Design
    • Social Media Marketing
    • Projects
  • Blog
    • PyTorch
    • Python
    • JavaScript
  • IT Institute
menu
close

Need Help? Talk to an Expert

+91 8000107255
Sprint Chase Technologies
  • Home
  • About
    • Why Choose Us
    • Contact Us
    • Team Members
    • Testimonials
  • Services
    • Web Development
    • Web Application Development
    • Mobile Application Development
    • Web Design
    • UI/UX Design
    • Social Media Marketing
    • Projects
  • Blog
    • PyTorch
    • Python
    • JavaScript
  • IT Institute

Need Help? Talk to an Expert

+91 8000107255

torch.randint(): Generating a Tensor with Random Integers

Home torch.randint(): Generating a Tensor with Random Integers
PyTorch torch.randint() Function
  • Written by krunallathiya21
  • April 20, 2025
  • 0 Com
PyTorch

The torch.randint() is a PyTorch factory function that generates tensors filled with random integers uniformly formed from a specified range [low, high]. You can generate on a CPU or a GPU.

torch.randint()

In the above figure, we generated a tensor of four integers, ranging from 0 (inclusive) to 8 (exclusive). So, it will generate random numbers between 0 to 7.

For the output consistency and reproducibility, you can control the seed. 

This method is helpful when you need to create a quick prototype and want to generate random integers instantly.

To control the dimensions of the output tensor precisely, use size tuples such as ((N,), (N, M), etc.).

If you want to create large-scale random sampling tensors, always favor torch.randint() over Python loops for efficiency.

Function Signature

torch.randint(
    low
    high
    size,
    generator = None,
    dtype = torch.int64,
    layout = torch.strided,
    device = None,
    requires_grad = False,
    out = None
) → Tensor

Arguments

Name Value
low (int, optional) It is an inclusive lower bound of the random integers.
high (int) It is an exclusive upper range of the random integer. From inclusive lower to exclusive upper, random integers will be generated.
size (tuple of integers) It determines the shape of the output tensor.
generator (torch.generator, optional) You can use this argument for reproducibility.
dtype (torch.dtype, optional) It determines the desired data type of the output tensor. By default, it is torch.int64.
layout (torch.layout, optional) It is a memory layout for the output tensor. By default, it is torch.strided.
device (torch.device, optional) You can use this argument to choose the device. For example, “CPU” or “cuda:0”.
requires_grad (bool, optional) If you set it to True, gradients will be tracked for this tensor.
out (Tensor, optional) It is the output tensor.

Simple tensor creation

Let’s generate a 1D tensor of shape(4, ) with values [0, 8) on the CPU:

import torch

rand_integers = torch.randint(0, 8, (4, ))

print(rand_integers)

# Output: tensor([7, 1, 3, 7])

# Your output may differ from my output because its random integer!

You can see that the output tensor has four elements, and these elements range from 0 to 7 (note that 8 is excluded).

Varying size

You can create a 0-dimensional tensor (0D) or you can call it “scalar tensor”, 1D tensor, or empty tensor, and higher dimensions like 3D, 4D, etc.

Scalar (0‑dim tensor)

import torch

rand_integers = torch.randint(0, 4, ())

print(rand_integers)
# Output: tensor(1)

print(rand_integers.shape)
# Output: torch.Size([])

You can see that the output is just a scalar tensor containing just 1 random integer.

We have already seen 1D tensors in this tutorial.

2D random tensors

import torch

rand_integers = torch.randint(0, 5, (2, 3))

print(rand_integers)
# Output: tensor([[3, 3, 4],
#                 [1, 0, 2]])

print(rand_integers.shape)
# Output: torch.Size([2, 3])

3D random tensors

import torch

rand_integers = torch.randint(0, 9, (2, 2, 2))

print(rand_integers)
# Output:
# tensor([[[0, 8],
#          [6, 7]],

#         [[4, 1],
#          [7, 2]]])

print(rand_integers.shape)
# Output: torch.Size([2, 2, 2])

Empty tensors

If any dimension is 0, it will generate an empty tensor.
import torch

rand_integers = torch.randint(0, 3, (0, 4))

print(rand_integers)
# Output: tensor([], size=(0, 4), dtype=torch.int64)

print(rand_integers.shape)
# Output: torch.Size([0, 4])

Varying low/high

Standard positive range

import torch

rand_integers = torch.randint(1, 8, (3,))

print(rand_integers)

# Output: tensor([7, 5, 6])

In this code, the low is 1, and the high is 8. Note that 8 is exclusive, but 1 is inclusive. Both ends are positive.

Negative to positive

import torch

rand_integers = torch.randint(-4, 4, (5,))

print(rand_integers)

# Output: tensor([ 1, -3, -2, -4, -1])

You can see that integers can be both negative and positive, but within a specific range and a high limit, excluding the high limit.

Invalid range (error)

RuntimeError while using torch.randint() You need to ensure that low is less than high, and both are not the same; otherwise, as you can see, PyTorch raises a RuntimeError.
import torch

rand_integers = torch.randint(5, 5, (2,))

print(rand_integers)

# Output: RuntimeError: random_ expects 'from' to be less than 'to', but got from=5 >= to=5

In the above code, high and low are the same [5, 5), we get the RuntimeError.

Specifying device

If you want to generate a tensor on CUDA, you can do that by specifying device=”cuda:0″.

rand_integers = torch.randint(0, 8, (4, ), device="cuda:0")

# Output: tensor([1, 6, 1, 4])
This approach is helpful when you need to feed random data to the GPU.

Specifying Dtype

You can specify a different data type by using the dtype argument. Let’s go for the torch.int32 type.
import torch

rand_integers = torch.randint(0, 8, (4, ), dtype=torch.int32)

print(rand_integers)

# Output: tensor([7, 3, 1, 5], dtype=torch.int32)

Reproducibility

For deterministic output, you can use torch.Generator().manual_seed() method.

And pass this generator to the .randint() method to reproduce the same random integers again and again.

import torch

gen = torch.Generator().manual_seed(42)

rand_integers = torch.randint(0, 8, (4, ), generator=gen)

print(rand_integers)

# Output: tensor([6, 3, 4, 6])
# Output: tensor([6, 3, 4, 6])
# Output: tensor([6, 3, 4, 6])

We ran the output three times, and each time, it produced the same result.

Gradient‑Tracking

It allows gradients through random tensors. Python does not support gradients for integers. We need to explicitly convert the generated integers to torch.float32 to allow gradient calculation.

import torch

# Generate integers
# then convert them to float tensors and enable gradient computation
rand_integers = torch.randint(
    0, 8, (4,), dtype=torch.float32, requires_grad=True)

loss = rand_integers.sum()

loss.backward()

print(rand_integers.grad)

# Output: tensor([1., 1., 1., 1.])

For mixed precision flows, you can cast the integer tensors into floats.

Post Views: 47
LEAVE A COMMENT Cancel reply
Please Enter Your Comments *

krunallathiya21

All Categories
  • JavaScript
  • Python
  • PyTorch
site logo

Address:  TwinStar, South Block – 1202, 150 Ft Ring Road, Nr. Nana Mauva Circle, Rajkot(360005), Gujarat, India

sprintchasetechnologies@gmail.com

(+91) 8000107255.

ABOUT US
  • About
  • Team Members
  • Testimonials
  • Contact

Copyright by @SprintChase  All Rights Reserved

  • PRIVACY
  • TERMS & CONDITIONS