Write a simple function

Beam lets you effortlessly run your code in the cloud—just as easily as running code locally.

Let’s start by writing a simple function that takes an input, prints something to the console, and returns an output.

To make this function work with Beam, we just wrap it in a decorator, @function.

app.py
from beam import function
import sys


@function(cpu=0.125)
def f(i):
    if i % 2 == 0:
        print("hello", i)
    else:
        print("world", i, file=sys.stderr)

    return i * i

Running the function locally, remotely, and in parallel

Beam gives you three different ways to run this function:

  1. As a regular call on your local machine, with f.local
  2. As a remote call that runs in the cloud, with f.remote
  3. In parallel, by calling f.map, which runs many copies of f simultaneously in the cloud.

We call f in each of these ways inside the main function below.

app.py
@function()
def main():
    # run the function locally
    print(f.local(5))

    # run the function remotely on Beam
    print(f.remote(5))

    # run the function in parallel and remotely on Beam
    total = 0
    for ret in f.map(range(10)):
        total += ret

    print(total)


if __name__ == "__main__":
    main()

Run python app.py in a shell, and you’ll see a Beam app start up. You’ll then see the printed logs of the main function and, mixed in with them, all the logs of f as it is run locally, then remotely, and then remotely and in parallel.

That’s all triggered by adding the @function decorator on main, which defines it as the function to start from locally when we invoke it.

What just happened?

When you called .remote on f, Beam seamlessly executed your function in the cloud, handling all the infrastructure behind the scenes.

In short, we took the function f, put it inside a container, sent it the inputs, and streamed back the logs and outputs.

Try something more interesting

The function f doesn’t do much, but imagine doing something more interesting instead:

Beam lets you parallelize these operations effortlessly by running hundreds or thousands of containers in the cloud.