transformers philosophy

In this file, we would like to sum up the core philosophy amd coding standards that we go by when reviewing PRs.

API

Transformers API

Code

Code style/quality

  1. Simplicity

Aim for simple code, and help our contributors with your knowledge of the library, of torch, of python etc. Doubt them, think about vectorizing, think about our API in general etc.

We probably already have EVERYTHING implemented in transformers let’s not re-invent boiling water, and look for the closest model / closest implementation.

  1. Readability

Let’s make the code readable. Once you simplify you should ask to split in 2 lines wherever possible, and look at Gemma or Llava for what an almost ideal model looks like

  1. Explainability

Code to be self-explanatory, easy to debug, easy to re-use. This means, no single letter variables, variable names that explain what is happening.

But also sources of new class / code. If there is a new MyAwesomeAttention , should link to the original implementation, code or repo where it was introduced. We don’t add Mr XXX’s custom design code.

Understandable code >> short code

Don’t try to make the code shorter if it harms readability. A lot of users dive into the source code and tweak it (that’s why we have the one file per model policy), so we really want the code to be as clear as possible. That means:

Fragment code for easy debugging

[CODE STYLE]

It’s easier to debug code when each line does one operation instead of adding multiple .do_this() , .and_that() , also_this() , and_let_us_not_forget_that() in a single line. Similarly, avoid using lambda functions (except maybe when sorting things and providing a key function).

This will also make your code easier to read, in accordance with the previous point.

f-string >> everything else

[CODE STYLE]

We always use f-strings because they make code easier to read and are faster than any other option for formatting. The only exception is if a given string needs to be formatted with values that are not available right now.

Use proper errors in code, no asserts

[CODE STYLE]

Asserts can be disabled by the user if they execute their script with a flag. Therefore, they aren’t suitable for errors you want to raise all the time. In general in the source code, use a test and raise the appropriate exception with a clear message. In tests however, you can use assert statements.

< > Update on GitHub