Fiber implements an proof-of-concept Python decorator that rewrites a function

Related tags

Miscellaneousfiber
Overview

Fiber

Fiber implements an proof-of-concept Python decorator that rewrites a function so that it can be paused and resumed (by moving stack variables to a heap frame and adding if statements to simulate jumps/gotos to specific lines of code).

Then, using a trampoline function that simulates the call stack on the heap, we can call functions that recurse arbitrarily deeply without stack overflowing (assuming we don't run out of heap memory).

cache = {}

@fiber.fiber(locals=locals())
def fib(n):
    assert n >= 0
    if n in cache:
        return cache[n]
    if n == 0:
        return 0
    if n == 1:
        return 1
    cache[n] = fib(n-1) + fib(n-2)
    return cache[n]

print(sys.getrecursionlimit())  # 1000 by default

# https://www.wolframalpha.com/input/?i=fib%281010%29+mod+10**5
print(trampoline.run(fib, [1010]) % 10 ** 5) # 74305

Please do not use this in production.

TOC

How it works

A quick refresher on the call stack: normally, when some function A calls another function B, A is "paused" while B runs to completion. Then, once B finishes, A is resumed.

In order to move the call stack to the heap, we need to transform function A to (1) store all variables on the heap, and (2) be able to resume execution at specific lines of code within the function.

The first step is easy: we rewrite all local loads and stores to instead load and store in a frame dictionary that is passed into the function. The second is more difficult: because Python doesn't support goto statements, we have to insert if statements to skip the code prefix that we don't want to execute.

There are a variety of "special forms" that cannot be jumped into. These we must handle by rewriting them into a form that we do handle.

For example, if we recursively call a function inside a for loop, we would like to be able to resume execution on the same iteration. However, when Python executes a for loop on an non-iterator iterable it will create a new iterator every time. To handle this case, we rewrite for loops into the equivalent while loop. Similarly, we must rewrite boolean expressions that short circuit (and, or) into the equivalent if statements.

Lastly, we must replace all recursive calls and normal returns by instead returning an instruction to a trampoline to call the child function or return the value to the parent function, respectively.

To recap, here are the AST passes we currently implement:

  1. Rewrite special forms:
    • for_to_while: Transforms for loops into the equivalent while loops.
    • promote_while_cond: Rewrites the while conditional to use a temporary variable that is updated every loop iteration so that we can control when it is evaluated (e.g. if the loop condition includes a recursive call).
    • bool_exps_to_if: Converts and and or expressions into the equivalent if statements.
  2. promote_to_temporary: Assigns the results of recursive calls into temporary variables. This is necessary when we make multiple recursive calls in the same statement (e.g. fib(n-1) + fib(n-2)): we need to resume execution in the middle of the expression.
  3. remove_trivial_temporaries: Removes temporaries that are assigned to only once and are directly assigned to some other variable, replacing subsequent usages with that other variable. This helps us detect tail calls.
  4. insert_jumps: Marks the statement after yield points (currently recursive calls and normal returns) with a pc index, and inserts if statements so that re-execution of the function will resume at that program counter.
  5. lift_locals_to_frame: Replaces loads and stores of local variables to loads and stores in the frame object.
  6. add_trampoline_returns: Replaces places where we must yield (recursive calls and normal returns) with returns to the trampoline function.
  7. fix_fn_def: Rewrites the function defintion to take a frame parameter.

See the examples directory for functions and the results after each AST pass. Also, see src/trampoline_test.py for some test cases.

Performance

A simple tail-recursive function that computes the sum of an array takes about 10-11 seconds to compute with Fiber. 1000 iterations of the equivalent for loop takes 7-8 seconds to compute. So we are slower by roughly a factor of 1000.

lst = list(range(1, 100001))

# fiber
@fiber.fiber(locals=locals())
def sum(lst, acc):
    if not lst:
        return acc
    return sum(lst[1:], acc + lst[0])

# for loop
total = 0
for i in lst:
    total += i

print(total, trampoline.run(sum, [lst, 0]))  # 5000050000, 5000050000

We could improve the performance of the code by eliminating redundant if checks in the generated code. Also, as we statically know the stack variables, we can use an array for the stack frame and integer indexes (instead of a dictionary and string hashes + lookups). This should improve the performance significantly, but there will still probably be a large amount of overhead.

Another performance improvement is to inline the stack array: instead of storing a list of frames in the trampoline, we could variables directly in the stack. Again, we can compute the frame size statically. Based on some tests in a handwritten JavaScript implementation, this has the potential to speed up the code by roughly a factor of 2-3, at the cost of a more complex implementation.

Limitations

  • The transformation works on the AST level, so we don't support other decorators (for example, we cannot use functools.cache in the above Fibonacci example).

  • The function can only access variables that are passed in the locals= argument. As a consequence of this, to resolve recursive function calls, we maintain a global mapping of all fiber functions by name. This means that fibers must have distinct names.

  • We don't support some special forms (ternaries, comprehensions). These can easily be added as a rewrite transformation.

  • We don't support exceptions. This would require us to keep track of exception handlers in the trampoline and insert returns to the trampoline to register and deregister handlers.

  • We don't support generators. To add support, we would have to modify the trampoline to accept another operation type (yield) that sends a value to the function that called next(). Also, the trampoline would have to support multiple call stacks.

Possible improvements

  • Improve test coverage on some of the AST transformations.
    • remove_trivial_temporaries may have a bug if the variable that it is replaced with is reassigned to another value.
  • Support more special forms (comprehensions, generators).
  • Support exceptions.
  • Support recursive calls that don't read the return value.

Questions

Why didn't you use Python generators?

It's less interesting as the transformations are easier. Here, we are effectively implementing generators in userspace (i.e. not needing VM support); see the answer to the next question for why this is useful.

Also, people have used generators to do this; see one recent generator example.

Why did you write this?

  • A+ project for CS 61A at Berkeley. During the course, we created a Scheme interpreter. The extra credit question we to replace tail calls in Python with a return to a trampoline, with the goal that tail call optimization in Python would let us evaluate tail calls to arbitrary depth in Scheme, in constant space.

    The test cases for the question checked whether interpreting tail-call recursive functions in Scheme caused a Python stack overflow. Using this Fiber implementation, (1) without tail call optimization in our trampoline, we would still be able to pass the test cases (we just wouldn't use constant space) and (2) we can now evaluate any Scheme expression to arbitrary depth, even if they are not in tail form.

  • The React framework has an a bug open which explores a compiler transform to rewrite JavaScript generators to a state machine so that recursive operations (render, reconcilation) can be written more easily. This is necessary because some JavaScript engines still don't support generators.

    This project basically implements a rough version of that compiler transform as a proof of concept, just in Python. https://github.com/facebook/react/pull/18942

Contributing

See CONTRIBUTING.md for more details.

License

Apache 2.0; see LICENSE for more details.

Disclaimer

This is a personal project, not an official Google project. It is not supported by Google and Google specifically disclaims all warranties as to its quality, merchantability, or fitness for a particular purpose.

Owner
Tyler Hou
Tyler Hou
An easy-to-learn, dynamic, interpreted, procedural programming language

Gen Programming Language WARNING!! THIS LANGUAGE IS IN DEVELOPMENT. ANYTHING CAN CHANGE AT ANY MOMENT. Gen is a dynamic, interpreted, procedural progr

Gen Programming Language 7 Oct 17, 2022
The bidirectional mapping library for Python.

bidict The bidirectional mapping library for Python. Status bidict: has been used for many years by several teams at Google, Venmo, CERN, Bank of Amer

Joshua Bronson 1.2k Dec 31, 2022
An Airdrop alternative for cross-platform users only for desktop with Python

PyDrop An Airdrop alternative for cross-platform users only for desktop with Python, -version 1.0 with less effort, just as a practice. ##############

Bernardo Olisan 6 Mar 25, 2022
Python most simple|stupid programming language (MSPL)

Most Simple|Stupid Programming language. (MSPL) Stack - Based programming language "written in Python" Features: Interpretate code (Run). Generate gra

Kirill Zhosul 14 Nov 03, 2022
Python library for the analysis of dynamic measurements

Python library for the analysis of dynamic measurements The goal of this library is to provide a starting point for users in metrology and related are

Physikalisch-Technische Bundesanstalt - Department 9.4 'Metrology for the digital Transformation' 18 Dec 21, 2022
Mata kuliah Bahasa Pemrograman

praktikum2 MENGHITUNG LUAS DAN KELILING LINGKARAN FLOWCHART : OUTPUT PROGRAM : PENJELASAN : Tetapkan nilai pada variabel sesuai inputan dari user :

2 Nov 09, 2021
A simple script that can watch a list of directories for change and does some action

plot_watcher A simple script that can watch a list of directories and does some action when a specific kind of change happens In its current implement

Charaf Errachidi 12 Sep 10, 2021
This repo contains scripts that add functionality to xbar.

xbar-custom-plugins This repo contains scripts that add functionality to xbar. Usage You have to add scripts to xbar plugin folder. If you don't find

osman uygar 1 Jan 10, 2022
Todo-backend - Todo backend with python

Todo-backend - Todo backend with python

Julio C. Diaz 1 Jan 07, 2022
This repository contains Python Projects for Beginners as well as for Intermediate Developers built by Contributors.

Python Projects {Open Source} Introduction The repository was built with a tree-like structure in mind, it contains collections of Python Projects. Mo

Gaurav Pandey 115 Apr 30, 2022
0xFalcon - 0xFalcon Tool For Python

0xFalcone Installation Install 0xFalcone Tool: apt install git git clone https:/

Alharb7 6 Sep 24, 2022
This is a Poetry plugin that will make it possible to build projects using custom TOML files

Poetry Multiproject Plugin This is a Poetry plugin that will make it possible to build projects using custom TOML files. This is especially useful whe

David Vujic 69 Dec 25, 2022
A numbers extract from string python package

Made with Python3 (C) @FayasNoushad Copyright permission under MIT License License - https://github.com/FayasNoushad/Numbers-Extract/blob/main/LICENS

Fayas Noushad 4 Nov 28, 2021
A simple, light-weight and highly maintainable online judge system for secondary education

y³OJ a simple, light-weight and highly maintainable online judge system for secondary education 一个简单、轻量化、易于维护的、为中学信息技术学科课业教学设计的 Online Judge 系统。 Onlin

20 Oct 04, 2022
Telegram bot for Urban Dictionary.

Urban Dictionary Bot @TheUrbanDictBot A star ⭐ from you means a lot to us! Telegram bot for Urban Dictionary. Usage Deploy to Heroku Tap on above butt

Stark Bots 17 Nov 24, 2022
MiniJVM is simple java virtual machine written by python language, it can load class file from file system and run it.

MiniJVM MiniJVM是一款使用python编写的简易JVM,能够从本地加载class文件并且执行绝大多数指令。 支持的功能 1.从本地磁盘加载class并解析 2.支持绝大多数指令集的执行 3.支持虚拟机内存分区以及对象的创建 4.支持方法的调用和参数传递 5.支持静态代码块的初始化 不支

keguoyu 60 Apr 01, 2022
Notes on the Deep Learning book from Ian Goodfellow, Yoshua Bengio and Aaron Courville (2016)

The Deep Learning Book - Goodfellow, I., Bengio, Y., and Courville, A. (2016) This content is part of a series following the chapter 2 on linear algeb

hadrienj 1.7k Jan 07, 2023
A simple and efficient computing package for Genshin Impact gacha analysis

GGanalysisLite计算包 这个版本的计算包追求计算速度,而GGanalysis包有着更多计算功能。 GGanalysisLite包通过卷积计算分布列,通过FFT和快速幂加速卷积计算。 测试玩家得到的排名值rank的数学意义是:与抽了同样数量五星的其他玩家相比,测试玩家花费的抽数大于等于比例

一棵平衡树 34 Nov 26, 2022
Test for using pyIIIFpres for rara magnetica project

raramagnetica_pyIIIFpres Test for using pyIIIFpres for rara magnetica project. This test show how to use pyIIIFpres for creating mannifest compliant t

Giacomo Marchioro 1 Dec 03, 2021
The Official interpreter for the Pix programming language.

The official interpreter for the Pix programming language. Pix Pix is a programming language dedicated to readable syntax and usability Q) Is Pix the

Pix 6 Sep 25, 2022