LeRobot documentation

문서 문자열 작성

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

문서 문자열 작성

LeRobot의 API 참조 문서는 src/lerobot/의 docstring에서 직접 생성됩니다. docstring은 주석이 아니라 해당 객체에 대한 공개 문서이며, 아래 형식은 렌더러와 CI 체크가 파싱하는 형식입니다.

이 페이지가 계약서입니다. src/lerobot/의 공개된 항목을 추가하거나 수정하는 경우 이를 따르세요.

문서화되지 않은 공개 메서드는 보이지 않는 것과 같습니다. [[autodoc]]는 docstring이 없는 멤버를 조용히 건너뜁니다. 경고나 오류가 발생하지 않으며, 단순히 렌더링된 페이지에 표시되지 않습니다. 커버리지와 API 레퍼런스 완성도는 동일한 문제입니다.

예시 하나에서 포맷

Google 섹션 헤더, Hugging Face 유형 서식. 둘 다, 둘 중 하나만 아님.

def send_action(self, action: RobotAction, rate_hz: float = 30.0) -> RobotAction:
    """Command the robot to move to a target joint configuration.

    Values are clipped by the configured maximum relative target before reaching the motors, so the
    returned action may differ from the requested one.

    Args:
        action (`dict[str, float]`):
            Target values keyed by motor name, e.g. `{"shoulder_pan.pos": 0.0}`. Keys must match the
            robot's action features.
        rate_hz (`float`, *optional*, defaults to `30.0`):
            Control loop frequency.

    Returns:
        `dict[str, float]`: The action actually written to the motors after safety clipping.

    Raises:
        DeviceNotConnectedError: If the robot has not been connected.

    Example:
        ```python
        >>> from lerobot.robots.so_follower import SO101Follower, SO101FollowerConfig
        >>> robot = SO101Follower(SO101FollowerConfig(port="/dev/ttyACM0"))  # doctest: +SKIP
        >>> robot.connect()  # doctest: +SKIP
        >>> robot.send_action({"shoulder_pan.pos": 0.0})  # doctest: +SKIP
        ```
    """

이 페이지의 예시에서는 교차 참조가 생략되어 있습니다. 교차 참조의 문법과 코드 블록 내에서 표시할 수 없는 이유는 교차 참조를 참고하세요.

규칙

섹션

Args: · Returns: · Raises: · Yields: · Example: · Note:

그 순서대로입니다. 다른 섹션 헤더는 없습니다. 한 줄 요약이 먼저 오고, 그다음 선택 사항인 자유 형식 설명, 그리고 섹션이 이어집니다.

Args: 행은 기계에 의해 파싱됩니다

name (`type`, *optional*, defaults to `X`):
    Description, indented on its own line.

The *optional*, defaults to clause is checked against the real signature default by make check-docstrings. It is not decorative — if you write a default that has drifted from the code, CI fails. Omit the clause entirely for required parameters:

    Args:
        port (`str`):
            Serial port the arm is connected to, e.g. `/dev/ttyACM0`.
        max_relative_target (`float | dict[str, float]`, *optional*):
            Caps the magnitude of the relative positional target vector. `None` disables clipping.
        use_degrees (`bool`, *optional*, defaults to `True`):
            Keep `True` for backward compatibility with existing policies and datasets.

타입은 백틱으로 표기합니다. 기본값이 None이거나 다시 언급할 가치가 없는 경우, defaults to 없이 *optional*을 사용합니다.

is type-first

한 줄 들여쓰기, 먼저 유형을 입력한 다음 콜론(:)을 입력하고, 설명을 입력합니다:

    Returns:
        `dict[str, float]`: The action actually written to the motors after safety clipping.

Yields: 동일한 형태를 가집니다.

**Attributes**: , never 속성:

doc-builder는 Attributes:만 있는 경우를 Parameters:의 동의어로 해석하여, 속성이 생성자 인수로 렌더링되도록 합니다. 이는 조용히 잘못된 동작입니다. 속성이 생성자 인수와 다를 때는 -- 구분자를 사용하는 굵은 형식을 사용하세요:

class Robot(abc.ABC):
    """The base abstract class for all LeRobot-compatible robots.

    **Attributes**:
        - **config_class** (`type[RobotConfig]`) -- The expected configuration class for this robot.
        - **name** (`str`) -- The unique robot name used to identify this robot type.
    """

참고 --, :이 아닙니다.

교차 참조

doc-builder의 괄호 구문을 사용하세요: 사각 괄호로 감싸고 백틱으로 인용된 경로입니다. Sphinx 역할(:pymeth:, :pyattr:)은 지원되지 않으며 페이지에서 리터럴 텍스트로 렌더링됩니다.

원하는쓰기
메인 패키지의 클래스[Robot]
메서드, 전체 경로 표시[Robot.connect]
메서드, 이름만 표시[~Robot.connect]
중첩 경로[~robots.Robot.connect]
다른 HF 라이브러리의 객체[~accelerate.Accelerator]

~는 링크 텍스트에서만 경로를 제거합니다. 링크는 여전히 전체 경로로 해석됩니다.

doc-builder는 페이지 전체, 펜스 코드 블록 내부에서도 이 구문을 해석합니다. 이 페이지의 docstring 예제가 교차 참조 대신 일반 텍스트를 사용하는 이유입니다. 교차 참조가 포함된 코드 블록은 입력해야 하는 구문이 아니라 해석된 링크로 렌더링됩니다. 본인의 docstring에서는 교차 참조를 자유롭게 사용하십시오. 이 제한은 해당 구문에 대한 문서에만 적용됩니다.

Callouts

GitHub 스타일의 인용 블록을 사용하세요:

> [!TIP]
> Call this once at startup — it takes about two seconds.

> [!WARNING]
> Torque is disabled on disconnect. The arm will drop if it is holding a load.

<Tip> 컴포넌트는 doc-builder 기준으로 레거시이므로 새로 추가하지 마세요.

예제는 반드시 펜스로 감싸야 합니다

예제는 >>>를 포함하는 ```python 블록 안에 있습니다. 이 펜스가 코드 블록으로 렌더링되게 하는 요소이며, doctest 전처리기의 정규식이 찾는 대상이기도 합니다:

    Example:
        ```python
        >>> from lerobot.robots.so_follower import SO101FollowerConfig
        >>> cfg = SO101FollowerConfig(port="/dev/ttyACM0")
        >>> cfg.use_degrees
        True
        ```

>>>가 code fence 없이 사용되어도 여전히 수집됩니다. doctest는 docstring 어디에 있는 프롬프트든 찾습니다. 잃는 것은 렌더링이므로, 페이지에서 긴 글벽처럼 표시됩니다. 모든 예시에는 code fence가 필요합니다.

모든 예제는 CI에서 실행되거나 # doctest: +SKIP를 포함합니다. 하드웨어, GPU, 또는 Hub에서 다운로드를 수행하는 모든 예제는 +SKIP를 사용합니다:

    Example:
        ```python
        >>> robot.connect()  # doctest: +SKIP
        >>> policy = ACTPolicy.from_pretrained("lerobot/act_aloha_sim_transfer_cube_human")  # doctest: +SKIP
        ```

실행 가능한 예제가 포함된 파일을 utils/documentation_tests.txt에 추가합니다.

모듈의 3~5개 핵심 진입 지점에 예시를 배치하세요. 자명한 접근자(accessor)에 대한 예시는 노이즈입니다.

자주 마주하게 되는 세 가지 패턴

Config dataclasses

Configuration 필드는 과거에 각 필드 위에 # 주석으로 문서화되었습니다. doc-builder는 인라인 주석을 볼 수 없습니다 — 이러한 클래스는 모든 필드가 나열되지만 설명이 하나도 표시되지 않습니다. 클래스 docstring의 Args: 블록으로 이동하세요:

@dataclass
class SOFollowerConfig:
    """Configuration for SO-family follower arms.

    Args:
        port (`str`):
            Serial port the arm is connected to, e.g. `/dev/ttyACM0`.
        max_relative_target (`float | dict[str, float]`, *optional*):
            Caps the magnitude of the relative positional target vector. A scalar applies to all motors;
            a dict maps motor name to a per-motor cap. `None` disables clipping.
        use_degrees (`bool`, *optional*, defaults to `True`):
            Keep `True` for backward compatibility with existing policies and datasets.
    """

    port: str
    max_relative_target: float | dict[str, float] | None = None
    use_degrees: bool = True

doc-builder는 베이스 클래스에서 docstring을 상속하지 않습니다. LeRobot의 등록된 config 클래스는 종종 얇은 다중 상속 shim입니다:

@RobotConfig.register_subclass("so101_follower")
@dataclass
class SOFollowerRobotConfig(RobotConfig, SOFollowerConfig):
    pass

해당 클래스는 모든 필드를 설명 없이 렌더링합니다. 베이스 클래스가 아무리 잘 문서화되어 있더라도 마찬가지입니다. Args: 블록은 [[autodoc]]가 지정한 구체 클래스에 위치해야 하며, 상속된 필드도 포함해야 합니다.

기본 클래스, 그 다음 구체적인 하위 클래스

추상 베이스 클래스가 정석적인 계약을 정의합니다. 서브클래스는 이 계약에서 벗어난 부분만 문서화합니다. 예를 들어 포트 의미론, 보정 특이사항, 모터 레이아웃, 지원되는 기능 키 등이 해당됩니다. 베이스 클래스의 계약을 모든 서브클래스에 중복해서 작성하지 마세요.

Robot, Teleoperator, Camera, MotorsBusBase, ProcessorStep, PreTrainedPolicy는 모두 이 형태를 따릅니다.

모듈 수준 별칭

여러 공개 이름은 별개의 클래스가 아닌 별칭입니다:

SO100FollowerConfig = SOFollowerRobotConfig
SO101FollowerConfig = SOFollowerRobotConfig

[[autodoc]]는 별명을 해석하여 정식 클래스 이름을 렌더링하므로, ## SO101FollowerConfig 제목은 본문에서 class lerobot.robots.so_follower.SOFollowerRobotConfig로 표시됩니다. 정식 클래스는 한 번만 문서화하고, 각 별명마다 별도의 autodoc 블록을 생성하는 대신 페이지의 본문에서 별명을 언급하세요.

문서화하지 말아야 할 것

  • 프라이빗 멤버. _로 시작하는 것은 공개 API의 일부가 아닙니다.
  • 문장으로 다시 서술된 타입 어노테이션. port (str): A string.은 아무것도 추가하지 않습니다. 용도를 설명하세요.
  • 업스트림에서 벤더링된 코드. src/lerobot/policies/molmoact2/molmoact2_hf_model/은 transformers에서 벤더링된 것으로, 이미 업스트림 스타일의 docstring을 포함하고 있습니다. 그대로 두세요. 다시 스타일을 조정하면 다음 동기화 시 충돌만 발생합니다. API 참조 문서와 docstring 검사에서 제외됩니다.

이것이 어떻게 강제되는지

확인이것이 감지하는 것
make check-docstringsArgs: 항목 중 시그니처와 일치하지 않거나, 실제 값과 달라진 문서화된 기본값
make doctest더 이상 실행되지 않는 예제
make check-doctest-listutils/documentation_tests.txt의 오래되었거나 정렬되지 않은 항목
ruff (D 규칙)Google 컨벤션 스타일 위반
interrogate현재 임계값보다 Docstring 커버리지가 낮아지는 경우
doc-builder존재하지 않는 대상에 가리키는 [[autodoc]] 경로 — 이는 문서 빌드를 깨뜨립니다

PR을 열기 전에 함께 실행하세요:

make check-docstrings && make doctest && pre-commit run --all-files

그런 다음 페이지를 렌더링하고 실제로 확인해 보세요:

doc-builder build lerobot docs/source/ --build_dir /tmp/doc-build

체크리스트

  • 수정한 모든 공개 멤버에는 docstring이 있습니다.
  • 모든 Args: 항목은 *optional*, defaults to 절을 포함하여 시그니처와 일치합니다.
  • Returns:는 들여쓰기 한 줄에 타입 우선으로 표시됩니다.
  • 맨 앞에 Attributes:를 단독으로 사용하지 마세요. -- 구분자를 사용하여 **Attributes**:를 사용하세요.
  • Sphinx 역할 없음 — 교차 참조에 [~module.Class.method]를 사용합니다.
  • 예제는 ```python 블록 안에 있으며, CI에서 실행되거나 # doctest: +SKIP를 포함합니다.
  • Config dataclass 필드는 # 주석이 아니라 구체 클래스의 Args: 블록에 있습니다.
  • 렌더링된 페이지를 육안으로 확인했습니다.
Update on GitHub