Skip to content

← Orientation and the Grade step 1 of 3

Easy Primitives

Count the tensor operations

Jump to the task

This exercise measures the number of tensor operations seen by an eager PyTorch dispatch counter. Consider two expressions:

import torch

x = torch.tensor([0.0, 0.5, 2.0])
literal = (x + 1) * 2 - 3
simplified = x * 2 - 1
print(literal.tolist())     # [-1.0, 0.0, 3.0]
print(simplified.tolist())  # [-1.0, 0.0, 3.0]

Expanding the brackets gives 2x + 2 - 3, then 2x - 1. The literal eager expression uses an addition, multiplication and subtraction. The simplified one uses just multiplication and subtraction.

What the counter tells you

The harness observes dispatched tensor operations while your function runs. It creates the input before counting and converts the output to a list afterwards. For these expressions, it records three operations versus two.

This is not a count of device kernels or complete passes through memory. Some operations return views, some launch multiple kernels, and compiled execution can behave differently. Fewer dispatches can reduce overhead or intermediate results, but they do not prove a proportional runtime improvement.

Algebra and floating-point arithmetic

The two expressions are equal over real numbers, but floating-point operations round intermediate values. Changing their order can change the result for some inputs. The small test values here give the same answer in both forms. For general numerical code, check error tolerances before treating an algebraic rewrite as an exact replacement.

Your task

def transform(x: torch.Tensor) -> torch.Tensor

Compute x * 2 - 1 elementwise for a float32 tensor using exactly two dispatched tensor operations. This is the simplified form of the starter's expression. For [0.0, 1.0, 2.0], return [-1.0, 1.0, 3.0].

The harness returns your values and the operation count under ops. This introductory exercise expects ops=2, rather than a general at-most budget. A Python scalar operand such as the 2 in x * 2 does not require a separate broadcast operation in this eager expression.