diff --git a/.github/workflows/build-default-models.yaml b/.github/workflows/build-default-models.yaml index 6feb5a616d..7edb860c1f 100644 --- a/.github/workflows/build-default-models.yaml +++ b/.github/workflows/build-default-models.yaml @@ -77,9 +77,8 @@ jobs: build_small_model: needs: resolve if: ${{ inputs.target == 'small' }} - runs-on: [self-hosted, tici] + runs-on: ubuntu-24.04-arm env: - MODELS_DIR: openpilot/selfdrive/modeld/models COMPILER: tinygrad_repo/examples/openpilot SMALL_ONNX: openpilot/selfdrive/modeld/models/driving_supercombo.onnx SMALL_PKL: openpilot/selfdrive/modeld/models/driving_tinygrad.pkl @@ -91,37 +90,28 @@ jobs: - name: Pull small ONNX via LFS run: ./lfs.py pull --exclude='' # ponytail: pulls every LFS file (lfs.py has no include filter); HF egress is free + - uses: actions/setup-python@v5 + with: + python-version: '3.12' - - name: Set environment variables - run: | - source /etc/profile - export UV_PROJECT_ENVIRONMENT=${HOME}/venv - export UV_PYTHON_PREFERENCE=managed - export UV_PYTHON_INSTALL_DIR=${HOME}/uv/python - export VIRTUAL_ENV=$UV_PROJECT_ENVIRONMENT - uv sync --frozen - printenv >> $GITHUB_ENV - - - name: Disable powersave - run: | - source ${UV_PROJECT_ENVIRONMENT}/bin/activate - PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --disable + - name: Set up the qcom mock + uses: ./.github/workflows/setup-qcom-mock + with: + hf_token: ${{ secrets.HF_TOKEN }} - name: Compile small model from ONNX run: | - source ${UV_PROJECT_ENVIRONMENT}/bin/activate - export PYTHONPATH="${PYTHONPATH}:${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}" - TG_FLAGS="DEV=QCOM IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1" + export PYTHONPATH="${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}" + TG_FLAGS="DEV=MOCK+QCOM HCQ_RUNTIME_DEV=CPU:LLVM:arm64,cortex-a75,fp-armv8,sha2,lse,neon,crc,aes IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1" env ${TG_FLAGS} python3 ${{ github.workspace }}/${{ env.COMPILER }}/compile_onnx.py \ ${{ github.workspace }}/${{ env.SMALL_ONNX }} \ ${{ github.workspace }}/${{ env.SMALL_PKL }} \ - --out-of-band --benchmark-runs 1 + --out-of-band --benchmark-runs 0 - name: Prepare output env: MODEL_NAME: ${{ needs.resolve.outputs.safe_model_name }} run: | - source ${UV_PROJECT_ENVIRONMENT}/bin/activate export PYTHONPATH=${{ github.workspace }} MODELS_DIR="${{ github.workspace }}/openpilot/selfdrive/modeld/models" OUTPUT_DIR="${{ github.workspace }}/small_output" @@ -153,19 +143,11 @@ jobs: name: artifact-name-${{ needs.resolve.outputs.safe_model_name }} path: ${{ github.workspace }}/small_output/artifact_name.txt - - name: Re-enable powersave - if: always() - run: | - source ${UV_PROJECT_ENVIRONMENT}/bin/activate - PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --enable - build_big_model: needs: resolve if: ${{ inputs.target == 'big' }} - runs-on: [self-hosted, chestnut] + runs-on: ubuntu-24.04 env: - MODELS_DIR: openpilot/selfdrive/modeld/models - COMPILER: tinygrad_repo/examples/openpilot BIG_PKL: openpilot/selfdrive/modeld/models/big_driving_tinygrad.pkl steps: - uses: actions/checkout@v4 @@ -175,43 +157,23 @@ jobs: - name: Pull big PKL via LFS run: ./lfs.py pull --exclude='' # ponytail: pulls every LFS file (lfs.py has no include filter); HF egress is free - - name: Set environment variables - run: | - source /etc/profile - export UV_PROJECT_ENVIRONMENT=${HOME}/venv - export UV_PYTHON_PREFERENCE=managed - export UV_PYTHON_INSTALL_DIR=${HOME}/uv/python - export VIRTUAL_ENV=$UV_PROJECT_ENVIRONMENT - uv sync --frozen - printenv >> $GITHUB_ENV + - uses: actions/setup-python@v5 + with: + python-version: '3.12' - - name: Disable powersave - run: | - source ${UV_PROJECT_ENVIRONMENT}/bin/activate - PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --disable + - name: Install LLVM 20 and ROCm comgr for the amd mock + uses: ./.github/workflows/setup-amd-mock + with: + emu_cache: big-warp - - name: Wait for chestnut PCIe link - run: | - source ${UV_PROJECT_ENVIRONMENT}/bin/activate - export PYTHONPATH="${PYTHONPATH}:${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}" - python3 -c " - import time - from openpilot.sunnypilot.modeld_v2.compile_modeld import chestnut_link_up - for i in range(10): - if chestnut_link_up(): - print(f'PCIe link up after {i+1} attempt(s)') - break - time.sleep(1) - else: - raise RuntimeError('Chestnut PCIe link not ready after 10 attempts') - " + - name: Install the amd mock build dependencies + run: python3 -m pip install -q numpy zstandard - name: Compile big warp run: | - source ${UV_PROJECT_ENVIRONMENT}/bin/activate - export PYTHONPATH="${PYTHONPATH}:${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}" + export PYTHONPATH="${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}" - CHESTNUT_TG_FLAGS="DEBUG=1 DEV=USB+AMD:LLVM FRAME_DEV=CPU FLOAT16=1 JIT_BATCH_SIZE=0 GMMU=0 TC_OPT=2 TC_MIN_GLOBALS=32" + CHESTNUT_TG_FLAGS="DEBUG=1 DEV=USB+AMD:LLVM FRAME_DEV=CPU FLOAT16=1 JIT_BATCH_SIZE=0 GMMU=0 CHECK_OOB=0 TC_OPT=2 TC_MIN_GLOBALS=32" COMPILER="${{ github.workspace }}/tinygrad_repo/examples/openpilot" MODELS_DIR="${{ github.workspace }}/openpilot/selfdrive/modeld/models" MODEL_SIZE=$(python3 -c "from openpilot.common.transformations.model import MEDMODEL_INPUT_SIZE as s; print(f'{s[0]}x{s[1]}')") @@ -226,11 +188,13 @@ jobs: print(f'{s},{y},{u},{sz}') " $CAM_W $CAM_H) WARP_PKL="${MODELS_DIR}/big_driving_warp_${res}_tinygrad.pkl" - env ${CHESTNUT_TG_FLAGS} python3 "${COMPILER}/compile_warp.py" \ + python3 tinygrad_repo/test/mockgpu/usb_server.py env PYTHONPATH="$PYTHONPATH" ${CHESTNUT_TG_FLAGS} python3 "${COMPILER}/compile_warp.py" \ --frame ${CAM_W},${CAM_H},${STRIDE_INFO} \ --warp-to ${MODEL_SIZE} \ --layout yuv420 \ --frames 2 \ + --benchmark-runs 0 \ + --retargetable \ --output "${WARP_PKL}" done @@ -238,7 +202,6 @@ jobs: env: MODEL_NAME: ${{ needs.resolve.outputs.safe_model_name }} run: | - source ${UV_PROJECT_ENVIRONMENT}/bin/activate export PYTHONPATH=${{ github.workspace }} MODELS_DIR="${{ github.workspace }}/openpilot/selfdrive/modeld/models" OUTPUT_DIR="${{ github.workspace }}/big_output" @@ -272,12 +235,6 @@ jobs: name: artifact-name-${{ needs.resolve.outputs.safe_model_name }} path: ${{ github.workspace }}/big_output/artifact_name.txt - - name: Re-enable powersave - if: always() - run: | - source ${UV_PROJECT_ENVIRONMENT}/bin/activate - PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --enable - upload_defaults: needs: [ resolve, build_small_model, build_big_model, build_dm_model ] if: | @@ -405,7 +362,7 @@ jobs: build_dm_model: needs: resolve if: ${{ inputs.target == 'dm' }} - runs-on: [self-hosted, tici] + runs-on: ubuntu-24.04-arm env: DM_ONNX: openpilot/selfdrive/modeld/models/dmonitoring_model.onnx DM_PKL: openpilot/selfdrive/modeld/models/dmonitoring_model_tinygrad.pkl @@ -417,40 +374,32 @@ jobs: - name: Pull DM ONNX via LFS run: ./lfs.py pull --exclude='' # ponytail: pulls every LFS file (lfs.py has no include filter); HF egress is free - - name: Set environment variables - run: | - source /etc/profile - export UV_PROJECT_ENVIRONMENT=${HOME}/venv - export UV_PYTHON_PREFERENCE=managed - export UV_PYTHON_INSTALL_DIR=${HOME}/uv/python - export VIRTUAL_ENV=$UV_PROJECT_ENVIRONMENT - uv sync --frozen - printenv >> $GITHUB_ENV + - uses: actions/setup-python@v5 + with: + python-version: '3.12' - - name: Disable powersave - run: | - source ${UV_PROJECT_ENVIRONMENT}/bin/activate - PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --disable + - name: Set up the qcom mock + uses: ./.github/workflows/setup-qcom-mock + with: + hf_token: ${{ secrets.HF_TOKEN }} - name: Compile DM model run: | - source ${UV_PROJECT_ENVIRONMENT}/bin/activate - export PYTHONPATH="${PYTHONPATH}:${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}" + export PYTHONPATH="${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}" - TG_FLAGS="DEV=QCOM IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1" + TG_FLAGS="DEV=MOCK+QCOM HCQ_RUNTIME_DEV=CPU:LLVM:arm64,cortex-a75,fp-armv8,sha2,lse,neon,crc,aes IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1" - taskset -c 7 env ${TG_FLAGS} python3 \ + env ${TG_FLAGS} python3 \ ${{ github.workspace }}/tinygrad_repo/examples/openpilot/compile_onnx.py \ ${{ github.workspace }}/${{ env.DM_ONNX }} \ ${{ github.workspace }}/${{ env.DM_PKL }} \ - --out-of-band --benchmark-runs 1 + --out-of-band --benchmark-runs 0 - name: Compile DM warp run: | - source ${UV_PROJECT_ENVIRONMENT}/bin/activate - export PYTHONPATH="${PYTHONPATH}:${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}" + export PYTHONPATH="${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}" - TG_FLAGS="DEV=QCOM IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1" + TG_FLAGS="DEV=MOCK+QCOM HCQ_RUNTIME_DEV=CPU:LLVM:arm64,cortex-a75,fp-armv8,sha2,lse,neon,crc,aes IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1" COMPILER="${{ github.workspace }}/tinygrad_repo/examples/openpilot" MODELS_DIR="${{ github.workspace }}/openpilot/selfdrive/modeld/models" DM_SIZE=$(python3 -c "from openpilot.common.transformations.model import DM_INPUT_SIZE as s; print(f'{s[0]}x{s[1]}')") @@ -465,12 +414,13 @@ jobs: print(f'{s},{y},{u},{sz}') " $CAM_W $CAM_H) WARP_PKL="${MODELS_DIR}/dm_warp_${res}_tinygrad.pkl" - taskset -c 7 env ${TG_FLAGS} python3 "${COMPILER}/compile_warp.py" \ + env ${TG_FLAGS} python3 "${COMPILER}/compile_warp.py" \ --frame ${CAM_W},${CAM_H},${STRIDE_INFO} \ --warp-to ${DM_SIZE} \ --layout luma \ --border-fill 16 \ --transform-device NPY \ + --benchmark-runs 0 \ --output "${WARP_PKL}" done @@ -485,9 +435,3 @@ jobs: with: name: dm-model-${{ github.run_number }} path: dm_output/ - - - name: Re-enable powersave - if: always() - run: | - source ${UV_PROJECT_ENVIRONMENT}/bin/activate - PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --enable diff --git a/.github/workflows/build-single-tinygrad-model.yaml b/.github/workflows/build-single-tinygrad-model.yaml index 7026a41914..ba28dae3fd 100644 --- a/.github/workflows/build-single-tinygrad-model.yaml +++ b/.github/workflows/build-single-tinygrad-model.yaml @@ -39,11 +39,6 @@ on: required: false type: string default: 'qcom' - on_device: - description: 'Compile on the tici / chestnut runner instead of on a hosted runner with tinygrad''s qcom / amd mock' - required: false - type: boolean - default: false hf_repo: description: 'Hugging Face dataset repository (e.g. sunnypilot/sunnypilot_models_v1)' required: false @@ -122,11 +117,6 @@ on: options: - qcom - chestnut - on_device: - description: 'Compile on the tici / chestnut runner instead of on a hosted runner with tinygrad''s qcom / amd mock' - required: false - type: boolean - default: false hf_repo: description: 'Hugging Face dataset repository' required: false @@ -151,7 +141,6 @@ jobs: is_20hz: ${{ inputs.is_20hz }} artifact_suffix: ${{ inputs.artifact_suffix }} target_hardware: ${{ inputs.target_hardware }} - on_device: ${{ inputs.on_device || false }} secrets: inherit publish_model: diff --git a/.github/workflows/compile-warp-kernels.yaml b/.github/workflows/compile-warp-kernels.yaml index 811c9bc017..d66ecadf26 100644 --- a/.github/workflows/compile-warp-kernels.yaml +++ b/.github/workflows/compile-warp-kernels.yaml @@ -3,58 +3,87 @@ name: Compile warp for sunnypilot modeld on: workflow_dispatch: +env: + WARP_DIR: openpilot/sunnypilot/modeld_v2/models + jobs: compile_warps: - runs-on: [self-hosted, chestnut] + strategy: + matrix: + include: + - target: qcom + runs-on: ubuntu-24.04-arm + prefix: driving_warp + flags: DEV=MOCK+QCOM IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1 + args: --split-frames + - target: chestnut + runs-on: ubuntu-24.04 + prefix: big_driving_warp + flags: DEV=MOCKUSB+AMD:LLVM FRAME_DEV=CPU FLOAT16=1 JIT_BATCH_SIZE=0 GMMU=0 CHECK_OOB=0 TC_OPT=2 TC_MIN_GLOBALS=32 + args: '' + runs-on: ${{ matrix.runs-on }} steps: - uses: actions/checkout@v4 with: submodules: recursive - - name: Set environment variables - run: | - source /etc/profile - export UV_PROJECT_ENVIRONMENT=${HOME}/venv - export UV_PYTHON_PREFERENCE=managed - export UV_PYTHON_INSTALL_DIR=${HOME}/uv/python - export VIRTUAL_ENV=$UV_PROJECT_ENVIRONMENT - uv sync --frozen - printenv >> $GITHUB_ENV + - uses: actions/setup-python@v5 + with: + python-version: '3.12' - - name: Disable powersave - run: | - source ${UV_PROJECT_ENVIRONMENT}/bin/activate - PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --disable + - name: Set up the qcom mock + if: matrix.target == 'qcom' + uses: ./.github/workflows/setup-qcom-mock + with: + hf_token: ${{ secrets.HF_TOKEN }} + + - name: Install LLVM 20 and ROCm comgr for the amd mock + if: matrix.target == 'chestnut' + uses: ./.github/workflows/setup-amd-mock + with: + emu_cache: warp + + - name: Install the amd mock build dependencies + if: matrix.target == 'chestnut' + run: python3 -m pip install -q numpy zstandard - name: Compile Warp Kernels run: | - source ${UV_PROJECT_ENVIRONMENT}/bin/activate - export PYTHONPATH="${PYTHONPATH}:${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}" - mkdir -p openpilot/sunnypilot/modeld_v2/models/ + export PYTHONPATH="${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}" + mkdir -p "$WARP_DIR" MODEL_SIZE=$(python3 -c "from openpilot.common.transformations.model import MEDMODEL_INPUT_SIZE as s; print(f'{s[0]}x{s[1]}')") CAMERA_RES=$(python3 -c "from openpilot.common.transformations.camera import _ar_ox_fisheye as a, _os_fisheye as o; print(f'{a.width}x{a.height} {o.width}x{o.height}')") - echo "Model size: $MODEL_SIZE" - echo "Camera resolutions: $CAMERA_RES" - for res in $CAMERA_RES; do FRAME_PARAM=$(python3 -c "from openpilot.system.camerad.cameras.nv12_info import get_nv12_info; w, h = map(int, '${res}'.split('x')); stride, y_h, uv_h, _ = get_nv12_info(w, h); print(f'{w},{h},{stride},{y_h},{uv_h},{stride * (y_h + uv_h)}')") - - WARP_PKL="openpilot/sunnypilot/modeld_v2/models/driving_warp_${res}_tinygrad.pkl" - echo "Compiling $WARP_PKL on QCOM" - taskset -c 7 env DEV=QCOM IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1 python3 openpilot/sunnypilot/modeld_v2/compile_warp.py \ - --frame ${FRAME_PARAM} --warp-to ${MODEL_SIZE} --split-frames --output "${WARP_PKL}" - - BIG_WARP_PKL="openpilot/sunnypilot/modeld_v2/models/big_driving_warp_${res}_tinygrad.pkl" - echo "Compiling $BIG_WARP_PKL on AMD" - taskset -c 7 env DEV=USB+AMD:LLVM FRAME_DEV=CPU FLOAT16=1 JIT_BATCH_SIZE=0 GMMU=0 TC_OPT=2 TC_MIN_GLOBALS=32 python3 openpilot/sunnypilot/modeld_v2/compile_warp.py \ - --frame ${FRAME_PARAM} --warp-to ${MODEL_SIZE} --output "${BIG_WARP_PKL}" + WARP_PKL="$WARP_DIR/${{ matrix.prefix }}_${res}_tinygrad.pkl" + echo "Compiling $WARP_PKL" + env ${{ matrix.flags }} python3 openpilot/sunnypilot/modeld_v2/compile_warp.py \ + --frame ${FRAME_PARAM} --warp-to ${MODEL_SIZE} ${{ matrix.args }} --output "${WARP_PKL}" done - - name: Re-enable powersave - if: always() - run: | - source ${UV_PROJECT_ENVIRONMENT}/bin/activate - PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --enable + - name: Replay their check frames on the mock and require the result bit for bit + env: + DEV: ${{ matrix.target == 'chestnut' && 'MOCKUSB+AMD' || 'MOCK+QCOM' }} + PYTHONPATH: ${{ github.workspace }}/tinygrad_repo:${{ github.workspace }} + run: python3 -m openpilot.sunnypilot.modeld_v2.mock_parity check "$WARP_DIR"/${{ matrix.prefix }}_*_tinygrad.pkl + + - uses: actions/upload-artifact@v4 + with: + name: warps-${{ matrix.target }} + path: ${{ env.WARP_DIR }}/${{ matrix.prefix }}_*_tinygrad.pkl + if-no-files-found: error + + create_pr: + needs: compile_warps + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + + - uses: actions/download-artifact@v4 + with: + pattern: warps-* + path: ${{ env.WARP_DIR }} + merge-multiple: true - name: Create Pull Request uses: peter-evans/create-pull-request@9153d834b60caba6d51c9b9510b087acf9f33f83 diff --git a/.github/workflows/setup-qcom-mock/action.yml b/.github/workflows/setup-qcom-mock/action.yml new file mode 100644 index 0000000000..f5dd2d7d0f --- /dev/null +++ b/.github/workflows/setup-qcom-mock/action.yml @@ -0,0 +1,62 @@ +name: Set up tinygrad's qcom mock +description: The a630 compiler, checked against what an a630 compiled, and the kernels earlier builds compiled +inputs: + hf_token: + description: Records a passed compiler check on HF so the next build skips it + default: '' +runs: + using: composite + steps: + - name: Install the qcom mock build dependencies + id: deps + shell: bash + run: | + python3 -m pip install -q numpy zstandard tinymesa==25.2.7.2 + if [ "$RUNNER_ARCH" = ARM64 ]; then # the qcomcl rootfs's compiler loads in this python, no qemu + sudo apt-get -qq update && sudo apt-get -qq install -y --no-install-recommends aria2 + FS=$(PYTHONPATH="$GITHUB_WORKSPACE/tinygrad_repo" python3 -c "from tinygrad.helpers import fetch; print(fetch('https://git.tinygrad.win/tinygrad/images/releases/download/v2/qcomcl.tar.gz', extract=True))") + echo "LLVM_QCOM_PATH=$FS/usr/lib/libllvm-qcom.so" >> "$GITHUB_ENV" + echo "compiler=native-$(sha256sum "$FS/usr/lib/libllvm-qcom.so" | cut -c1-16)" >> "$GITHUB_OUTPUT" + else + sudo apt-get -qq update && sudo apt-get -qq install -y --no-install-recommends qemu-user-static aria2 + echo "compiler=qemu-$(dpkg-query -W -f='${Version}' qemu-user-static)" >> "$GITHUB_OUTPUT" + fi + + - name: Compiler check passed before with all of it identical? + id: compiler + shell: bash + env: + KEY: qcom-compiler-parity-${{ steps.deps.outputs.compiler }}-${{ hashFiles('tinygrad_repo/test/device/qcom/compiler_parity.py', 'tinygrad_repo/test/mockgpu/qcom/a630_compiled.pkl.xz', 'tinygrad_repo/tinygrad/runtime/support/compiler_qcom.py') }} + run: | + MARKER="ci/qcom-compiler-parity/$(printf '%s' "$KEY" | tr -c 'A-Za-z0-9._-' '_').txt" + CODE=$(curl -s -o /dev/null -w '%{http_code}' -I -L "https://huggingface.co/datasets/sunnypilot/sunnypilot_models_v1/resolve/main/$MARKER") + echo "$MARKER: HTTP $CODE" + { echo "key=$KEY"; echo "marker=$MARKER"; echo "passed=$([ "$CODE" = 200 ] && echo true || echo false)"; } >> "$GITHUB_OUTPUT" + + - name: Check the off-device qcom compiler builds the a630's bytes + if: steps.compiler.outputs.passed != 'true' + shell: bash + run: | + # every kernel an a630 has compiled must compile to the same bytes here before a model is built here + TG="$GITHUB_WORKSPACE/tinygrad_repo" + PYTHONPATH="$TG" python3 "$TG/test/device/qcom/compiler_parity.py" check "$TG/test/mockgpu/qcom/a630_compiled.pkl.xz" + + - name: Remember the compiler check passed + if: steps.compiler.outputs.passed != 'true' && inputs.hf_token != '' + shell: bash + env: + HF_TOKEN: ${{ inputs.hf_token }} + KEY: ${{ steps.compiler.outputs.key }} + MARKER: ${{ steps.compiler.outputs.marker }} + run: | + python3 -m pip install -q --upgrade "huggingface_hub>=0.34" + printf '%s\n%s\n' "$KEY" "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" > "$RUNNER_TEMP/marker.txt" + hf upload --repo-type dataset sunnypilot/sunnypilot_models_v1 "$RUNNER_TEMP/marker.txt" "$MARKER" \ + --commit-message "qcom compiler parity passed: $KEY" || echo "::warning::could not record the pass, the next build checks again" + + - name: Kernels compiled by earlier builds + uses: actions/cache@v4 + with: + path: ~/.cache/tinygrad/cache.db + key: qcom-kernels-${{ steps.compiler.outputs.key }}-${{ github.run_id }} + restore-keys: qcom-kernels-${{ steps.compiler.outputs.key }}- diff --git a/.github/workflows/sunnypilot-build-model.yaml b/.github/workflows/sunnypilot-build-model.yaml index 9c9f73b19d..7a0e3c0d00 100644 --- a/.github/workflows/sunnypilot-build-model.yaml +++ b/.github/workflows/sunnypilot-build-model.yaml @@ -1,9 +1,7 @@ name: Build Model from Upstream env: - BUILD_DIR: "/data/openpilot" OUTPUT_DIR: ${{ github.workspace }}/output - SCONS_CACHE_DIR: ${{ github.workspace }}/release/ci/scons_cache UPSTREAM_REPO: "commaai/openpilot" TINYGRAD_PATH: ${{ github.workspace }}/tinygrad_repo MODELS_DIR: ${{ github.workspace }}/openpilot/selfdrive/modeld/models @@ -40,11 +38,6 @@ on: required: false type: string default: 'qcom' - on_device: - description: 'Compile on the tici / chestnut runner instead of on a hosted runner with tinygrad''s qcom / amd mock' - required: false - type: boolean - default: false workflow_dispatch: inputs: upstream_branch: @@ -74,11 +67,6 @@ on: - qcom - chestnut default: 'qcom' - on_device: - description: 'Compile on the tici / chestnut runner instead of on a hosted runner with tinygrad''s qcom / amd mock' - required: false - type: boolean - default: false run-name: Build model [${{ inputs.custom_name || inputs.upstream_branch }}] from ref [${{ inputs.upstream_branch }}] @@ -186,114 +174,36 @@ jobs: if-no-files-found: error build_model: - runs-on: ${{ inputs.on_device && fromJSON(inputs.target_hardware == 'chestnut' && '["self-hosted","chestnut"]' || '["self-hosted","tici"]') || inputs.target_hardware == 'chestnut' && 'ubuntu-24.04' || 'ubuntu-24.04-arm' }} + runs-on: ${{ inputs.target_hardware == 'chestnut' && 'ubuntu-24.04' || 'ubuntu-24.04-arm' }} needs: get_model env: MODEL_NAME: ${{ inputs.custom_name || inputs.upstream_branch }} (${{ needs.get_model.outputs.model_date }}) REF: ${{ inputs.upstream_branch }} - MOCK_BUILD: ${{ !inputs.on_device }} steps: - uses: actions/checkout@v4 with: fetch-depth: 1 submodules: recursive - - name: Set up the hosted mock build - if: env.MOCK_BUILD == 'true' - uses: actions/setup-python@v5 + - uses: actions/setup-python@v5 with: python-version: '3.12' - name: Install LLVM 20 and ROCm comgr for the amd mock - if: env.MOCK_BUILD == 'true' && inputs.target_hardware == 'chestnut' + if: inputs.target_hardware == 'chestnut' uses: ./.github/workflows/setup-amd-mock with: emu_cache: build - name: Install the amd mock build dependencies - if: env.MOCK_BUILD == 'true' && inputs.target_hardware == 'chestnut' - run: | - python3 -m pip install -q numpy zstandard + if: inputs.target_hardware == 'chestnut' + run: python3 -m pip install -q numpy zstandard - - name: Install the qcom mock build dependencies - if: env.MOCK_BUILD == 'true' && inputs.target_hardware != 'chestnut' - id: qcom_deps - run: | - python3 -m pip install -q numpy zstandard tinymesa==25.2.7.2 - if [ "$RUNNER_ARCH" = ARM64 ]; then # the qcomcl rootfs's compiler loads in this python, no qemu - sudo apt-get -qq update && sudo apt-get -qq install -y --no-install-recommends aria2 - FS=$(PYTHONPATH="$TINYGRAD_PATH" python3 -c "from tinygrad.helpers import fetch; print(fetch('https://git.tinygrad.win/tinygrad/images/releases/download/v2/qcomcl.tar.gz', extract=True))") - echo "LLVM_QCOM_PATH=$FS/usr/lib/libllvm-qcom.so" >> "$GITHUB_ENV" - echo "compiler=native-$(sha256sum "$FS/usr/lib/libllvm-qcom.so" | cut -c1-16)" >> "$GITHUB_OUTPUT" - else - sudo apt-get -qq update && sudo apt-get -qq install -y --no-install-recommends qemu-user-static aria2 - echo "compiler=qemu-$(dpkg-query -W -f='${Version}' qemu-user-static)" >> "$GITHUB_OUTPUT" - fi - - - name: Compiler check passed before with all of it identical? - if: env.MOCK_BUILD == 'true' && inputs.target_hardware != 'chestnut' - id: qcom_compiler - env: - KEY: qcom-compiler-parity-${{ steps.qcom_deps.outputs.compiler }}-${{ hashFiles('tinygrad_repo/test/device/qcom/compiler_parity.py', 'tinygrad_repo/test/mockgpu/qcom/a630_compiled.pkl.xz', 'tinygrad_repo/tinygrad/runtime/support/compiler_qcom.py') }} - run: | - MARKER="ci/qcom-compiler-parity/$(printf '%s' "$KEY" | tr -c 'A-Za-z0-9._-' '_').txt" - CODE=$(curl -s -o /dev/null -w '%{http_code}' -I -L "https://huggingface.co/datasets/sunnypilot/sunnypilot_models_v1/resolve/main/$MARKER") - echo "$MARKER: HTTP $CODE" - { echo "key=$KEY"; echo "marker=$MARKER"; echo "passed=$([ "$CODE" = 200 ] && echo true || echo false)"; } >> "$GITHUB_OUTPUT" - - - name: Check the off-device qcom compiler builds the a630's bytes - if: env.MOCK_BUILD == 'true' && inputs.target_hardware != 'chestnut' && steps.qcom_compiler.outputs.passed != 'true' - run: | - # every kernel an a630 has compiled must compile to the same bytes here before a model is built here - PYTHONPATH="$TINYGRAD_PATH" python3 "$TINYGRAD_PATH/test/device/qcom/compiler_parity.py" check "$TINYGRAD_PATH/test/mockgpu/qcom/a630_compiled.pkl.xz" - - - name: Remember the compiler check passed - if: env.MOCK_BUILD == 'true' && inputs.target_hardware != 'chestnut' && steps.qcom_compiler.outputs.passed != 'true' - env: - HF_TOKEN: ${{ secrets.HF_TOKEN }} - KEY: ${{ steps.qcom_compiler.outputs.key }} - MARKER: ${{ steps.qcom_compiler.outputs.marker }} - run: | - python3 -m pip install -q --upgrade "huggingface_hub>=0.34" - printf '%s\n%s\n' "$KEY" "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" > "$RUNNER_TEMP/marker.txt" - hf upload --repo-type dataset sunnypilot/sunnypilot_models_v1 "$RUNNER_TEMP/marker.txt" "$MARKER" \ - --commit-message "qcom compiler parity passed: $KEY" || echo "::warning::could not record the pass, the next build checks again" - - - name: Kernels compiled by earlier builds - if: env.MOCK_BUILD == 'true' && inputs.target_hardware != 'chestnut' - uses: actions/cache@v4 + - name: Set up the qcom mock + if: inputs.target_hardware != 'chestnut' + uses: ./.github/workflows/setup-qcom-mock with: - path: ~/.cache/tinygrad/cache.db - key: qcom-kernels-${{ steps.qcom_compiler.outputs.key }}-${{ github.run_id }} - restore-keys: qcom-kernels-${{ steps.qcom_compiler.outputs.key }}- - - - name: Set environment variables - if: env.MOCK_BUILD != 'true' - id: set-env - run: | - # Set up common environment - source /etc/profile; - export UV_PROJECT_ENVIRONMENT=${HOME}/venv - export UV_PYTHON_PREFERENCE=managed - export UV_PYTHON_INSTALL_DIR=${HOME}/uv/python - export VIRTUAL_ENV=$UV_PROJECT_ENVIRONMENT - uv sync --frozen - printenv >> $GITHUB_ENV - - - name: Setup build environment - if: env.MOCK_BUILD != 'true' - run: | - mkdir -p "${BUILD_DIR}/" - sudo find $BUILD_DIR/ -mindepth 1 -delete - echo "Starting build stage..." - echo "BUILD_DIR: ${BUILD_DIR}" - echo "CI_DIR: ${CI_DIR}" - echo "VERSION: ${{ steps.set-env.outputs.version }}" - echo "UV_PROJECT_ENVIRONMENT: ${UV_PROJECT_ENVIRONMENT}" - echo "VIRTUAL_ENV: ${VIRTUAL_ENV}" - source ${UV_PROJECT_ENVIRONMENT}/bin/activate - PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --disable - rm -rf ${{ env.MODELS_DIR }}/*.onnx* + hf_token: ${{ secrets.HF_TOKEN }} - name: Download model artifacts uses: actions/download-artifact@v4 @@ -303,28 +213,18 @@ jobs: - name: Build Model run: | - if [ "$MOCK_BUILD" = "true" ]; then - TASKSET="" - export CHECK_OOB=0 GMMU=0 # as test/mockgpu runs the amd mock - else - source /etc/profile - export UV_PROJECT_ENVIRONMENT=${HOME}/venv - export VIRTUAL_ENV=$UV_PROJECT_ENVIRONMENT - source ${UV_PROJECT_ENVIRONMENT}/bin/activate - TASKSET="taskset -c 7" - fi + export CHECK_OOB=0 GMMU=0 # as test/mockgpu runs the amd mock export PYTHONPATH="${PYTHONPATH}:${{ env.TINYGRAD_PATH }}:${{ github.workspace }}" COMPILE_MODELD="${{ github.workspace }}/openpilot/sunnypilot/modeld_v2/compile_modeld.py" MODEL_SIZE=$(python3 -c "from openpilot.common.transformations.model import MEDMODEL_INPUT_SIZE as s; print(f'{s[0]}x{s[1]}')") CAMERA_RES=$(python3 -c "from openpilot.common.transformations.camera import _ar_ox_fisheye as a, _os_fisheye as o; print(f'{a.width}x{a.height} {o.width}x{o.height}')") - MOCK=$([ "$MOCK_BUILD" = "true" ] && echo MOCK || true) - TG_FLAGS_QCOM="DEV=${MOCK:+MOCK+}QCOM IMAGE=1 FLOAT16=1 NOLOCALS=1 OPENPILOT_HACKS=1" + TG_FLAGS_QCOM="DEV=MOCK+QCOM IMAGE=1 FLOAT16=1 NOLOCALS=1 OPENPILOT_HACKS=1" if [ "${{ inputs.target_hardware }}" == "chestnut" ]; then echo "CHESTNUT build" export CHESTNUT=1 - TG_FLAGS="DEBUG=1 DEV=${MOCK}USB+AMD:LLVM FRAME_DEV=CPU FLOAT16=1 GMMU=0 TC_OPT=2 TC_MIN_GLOBALS=32" + TG_FLAGS="DEBUG=1 DEV=MOCKUSB+AMD:LLVM FRAME_DEV=CPU FLOAT16=1 GMMU=0 TC_OPT=2 TC_MIN_GLOBALS=32" OUTPUT_PKL="${{ env.MODELS_DIR }}/big_driving_tinygrad.pkl" else echo "QCOM build" @@ -339,17 +239,15 @@ jobs: echo "Converting commaai's precompiled model with tinygrad $TG_SHA" UPSTREAM_TG="${{ runner.temp }}/upstream_tinygrad" rm -rf "$UPSTREAM_TG" && git init -q "$UPSTREAM_TG" && git -C "$UPSTREAM_TG" fetch -q --depth 1 "$TG_URL" "$TG_SHA" && git -C "$UPSTREAM_TG" checkout -q FETCH_HEAD - ON_MOCK="" - if [ "$MOCK_BUILD" = "true" ]; then ON_MOCK="env PYTHONPATH=$TINYGRAD_PATH python3 $TINYGRAD_PATH/test/mockgpu/usb_server.py"; fi CONVERTED="${{ runner.temp }}/big_driving_tinygrad_plain.pkl" - $ON_MOCK env DEV=USB+AMD PYTHONPATH="$UPSTREAM_TG:${{ github.workspace }}" $TASKSET python3 openpilot/sunnypilot/modeld_v2/convert_upstream_pkl.py \ + env PYTHONPATH="$TINYGRAD_PATH" python3 "$TINYGRAD_PATH/test/mockgpu/usb_server.py" env DEV=USB+AMD PYTHONPATH="$UPSTREAM_TG:${{ github.workspace }}" python3 openpilot/sunnypilot/modeld_v2/convert_upstream_pkl.py \ "${{ env.MODELS_DIR }}/big_driving_tinygrad.pkl" "$CONVERTED" mv "$CONVERTED" "$OUTPUT_PKL" elif NEW_ARCH_ONNX=$(find "${{ env.MODELS_DIR }}" -maxdepth 1 -name "${{ inputs.target_hardware == 'chestnut' && 'big_' || '' }}*driving*.onnx" -print -quit) && [ -n "$NEW_ARCH_ONNX" ] && grep -qa new_img "$NEW_ARCH_ONNX"; then # the new architecture: one ONNX taking the warped frames as new_img echo "Compiling new architecture ONNX: $NEW_ARCH_ONNX" - env ${TG_FLAGS} $TASKSET python3 openpilot/sunnypilot/modeld_v2/compile_modeld_v2.py \ - "$NEW_ARCH_ONNX" "$OUTPUT_PKL" --device-input "*" --benchmark-runs $([ "$MOCK_BUILD" = "true" ] && echo 0 || echo 1) + env ${TG_FLAGS} python3 openpilot/sunnypilot/modeld_v2/compile_modeld_v2.py \ + "$NEW_ARCH_ONNX" "$OUTPUT_PKL" --device-input "*" --benchmark-runs 0 else echo "Detected onnx architecture. Routing to native compile_modeld.py." # Detect model type and build compile args @@ -398,7 +296,7 @@ jobs: if [ -n "$MODEL_TYPE" ]; then echo "Detected: $MODEL_TYPE -> $OUTPUT_PKL" - env ${TG_FLAGS} $TASKSET python3 "$COMPILE_MODELD" \ + env ${TG_FLAGS} python3 "$COMPILE_MODELD" \ --model-type $MODEL_TYPE \ --model-size $MODEL_SIZE \ --camera-resolutions $CAMERA_RES \ @@ -408,7 +306,6 @@ jobs: fi - name: Replay its check frame on the mock and require the result bit for bit - if: env.MOCK_BUILD == 'true' env: DEV: ${{ inputs.target_hardware == 'chestnut' && 'MOCKUSB+AMD' || 'MOCK+QCOM' }} PYTHONPATH: ${{ env.TINYGRAD_PATH }}:${{ github.workspace }} @@ -425,7 +322,6 @@ jobs: --include='/${{ inputs.target_hardware == 'chestnut' && 'big_' || '' }}driving_tinygrad.pkl' \ --exclude='*' \ --delete-excluded \ - $([ "$MOCK_BUILD" = "true" ] || echo --chown=comma:comma) \ ${{ env.MODELS_DIR }}/ ${{ env.OUTPUT_DIR }}/ python3 "${{ github.workspace }}/release/ci/model_generator.py" \ @@ -452,9 +348,3 @@ jobs: with: name: artifact-name-${{ inputs.custom_name || inputs.upstream_branch }} path: ${{ env.OUTPUT_DIR }}/artifact_name.txt - - - name: Re-enable powersave - if: always() && env.MOCK_BUILD != 'true' - run: | - source ${UV_PROJECT_ENVIRONMENT}/bin/activate - PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --enable diff --git a/openpilot/selfdrive/controls/lib/desire_helper.py b/openpilot/selfdrive/controls/lib/desire_helper.py index ed8be505f8..2a4339aad6 100644 --- a/openpilot/selfdrive/controls/lib/desire_helper.py +++ b/openpilot/selfdrive/controls/lib/desire_helper.py @@ -28,6 +28,8 @@ class DesireHelper: self.alc = AutoLaneChangeController(self) self.lane_turn_controller = LaneTurnController(self) self.lane_turn_direction = TurnDirection.none + self.turn_frames = 0 + self.turn_repulse = 98 @staticmethod def get_lane_change_direction(CS): @@ -95,8 +97,10 @@ class DesireHelper: self.prev_one_blinker = one_blinker and lateral_active if self.lane_turn_direction != TurnDirection.none: - self.desire = TURN_DESIRES[self.lane_turn_direction] + self.turn_frames += 1 + self.desire = TURN_DESIRES[self.lane_turn_direction] if self.turn_frames % self.turn_repulse else log.Desire.none else: + self.turn_frames = 0 self.desire = log.Desire.none if self.lane_change_state == LaneChangeState.laneChangeStarting: if self.lane_change_direction == LaneChangeDirection.left: diff --git a/openpilot/sunnypilot/modeld_v2/compile_modeld.py b/openpilot/sunnypilot/modeld_v2/compile_modeld.py index c5bfcc6640..2e7312e55a 100755 --- a/openpilot/sunnypilot/modeld_v2/compile_modeld.py +++ b/openpilot/sunnypilot/modeld_v2/compile_modeld.py @@ -370,38 +370,7 @@ def _compile_warp_resolution_worker(cam_w, cam_h, model_w, model_h, benchmark_ru write_bundle(result_path, {(cam_w, cam_h): compiled_jit}, {'device': Device.DEFAULT}) -def chestnut_link_up() -> bool: - # asm enumerates on USB-C alone, gpu is only usable once pcie link is up (upstream dropped flash.link_up in #39195) - import ctypes - import fcntl - from openpilot.system.hardware.chestnut.flash import USBDEVFS_CONTROL, Ctrl, find_chestnut, open_device - try: - path, _, _ = find_chestnut() - if path is None: - return False - fd = open_device(path) - except (OSError, RuntimeError): - return False - try: - fcntl.ioctl(fd, USBDEVFS_CONTROL, Ctrl(0x40, 0xF3, 1, 0, 0, 2000, None)) - buf = (ctypes.c_ubyte * 1)() - fcntl.ioctl(fd, USBDEVFS_CONTROL, Ctrl(0xC0, 0xE4, 0xB450, 0, 1, 1000, ctypes.cast(buf, ctypes.c_void_p))) - return buf[0] == 0x78 # LTSSM L0 - except OSError: - return False - finally: - os.close(fd) - - if __name__ == "__main__": - if ('USB' in os.getenv('DEV', '') or os.getenv('CHESTNUT')) and not os.getenv('DEV', '').startswith('MOCK'): - for _ in range(10): - if chestnut_link_up(): - break - time.sleep(1) - else: - raise RuntimeError("Chestnut not ready, skipping big model build") - parser = argparse.ArgumentParser(description="Compile combined JIT pkl for sunnypilot modeld_v2") parser.add_argument('--model-type', choices=MODEL_TYPES, required=True) parser.add_argument('--model-size', type=_parse_size, required=True, help='model input WxH') diff --git a/openpilot/sunnypilot/modeld_v2/compile_warp.py b/openpilot/sunnypilot/modeld_v2/compile_warp.py index 0997181c64..8e6d1dd959 100755 --- a/openpilot/sunnypilot/modeld_v2/compile_warp.py +++ b/openpilot/sunnypilot/modeld_v2/compile_warp.py @@ -17,6 +17,7 @@ def main(): parser.add_argument("--frame", required=True, help="width,height,stride,y_height,uv_height,buffer_size") parser.add_argument("--warp-to", required=True, help="model input WxH") parser.add_argument("--output", required=True) + parser.add_argument("--light", action="store_true") parser.add_argument("--split-frames", action="store_true", help="one input per camera (frame, big_frame), bound to the camera buffers by pointer") args = parser.parse_args() @@ -24,18 +25,20 @@ def main(): from tinygrad import Device, Tensor, TinyJit frame = parse_frame(args.frame) warp = make_frame_prepare(frame, *parse_size(args.warp_to)) + n = 1 if args.light else 2 + cams = list(range(n)) rng = np.random.default_rng(42) frames = rng.integers(0, 256, (2, frame.size), dtype=np.uint8) - m_inv = Tensor((rng.standard_normal((2, 3, 3)) * 8).astype(np.float32), device=Device.DEFAULT).realize() + m_inv = Tensor((rng.standard_normal((n, 3, 3)) * 8).astype(np.float32), device=Device.DEFAULT).realize() if args.split_frames: - run = TinyJit(lambda frame, big_frame, M_inv: Tensor.stack(warp(frame, M_inv[0]), warp(big_frame, M_inv[1])), prune=True) - inputs = {"frame": Tensor(frames[0], device=Device.DEFAULT).realize(), "big_frame": Tensor(frames[1], device=Device.DEFAULT).realize(), "M_inv": m_inv} - specs = {"frame": ((frame.size,), "|u1", Device.DEFAULT), "big_frame": ((frame.size,), "|u1", Device.DEFAULT), - "M_inv": ((2, 3, 3), " bytes: return b"\x7fELF\x02\x01\x01" + bytes(9) + header + data + b"".join(headers) +def lower_and_compile(linear): + try: + from tinygrad.codegen.compile import lower_and_compile + except ImportError: + from tinygrad.engine.realize import lower_and_compile + return lower_and_compile(linear) + + +def submit_kernels(jit) -> tuple: + info = jit.captured._linear.src[0].without_after.arg + return (info.hcq if hasattr(info, "hcq") else info.aux).kernels + + def convert(jit, kwargs: dict, frame: dict, target) -> tuple[dict, memoryview]: import tinygrad.runtime.autogen.am.pm4_nv as pm4 import tinygrad.runtime.autogen.amd_gpu as amd_gpu @@ -146,7 +159,9 @@ def convert(jit, kwargs: dict, frame: dict, target) -> tuple[dict, memoryview]: from tinygrad.helpers import unwrap from tinygrad.uop.ops import Ops submit = jit.captured._linear.src[0].without_after - kernels, topo = submit.arg.aux.kernels, list(jit.captured._linear.toposort(enter_calls=True)) + kernels, topo = submit_kernels(jit), list(jit.captured._linear.toposort(enter_calls=True)) + externs = dict(enumerate(getattr(jit.captured, "_externs", ()), len(_prepare_jit_inputs((), kwargs)[0]))) + buffer = lambda b: _buffer(externs.get(b.arg.slot, b) if b.op.name == "EXTERN" else b) # noqa: E731 allocs = {str(name): u for u in topo if u.op is Ops.ALLOC and (name := getattr(u, "tag", None) or u.arg.name) is not None} (commands, patched), kernargs = _patched(allocs["cmdbuf_compute_0"], topo), allocs["kernargs_compute_0"] argument_words, pokes = _patched(kernargs, topo)[1], _input_pokes(submit, kernargs) @@ -202,12 +217,12 @@ def convert(jit, kwargs: dict, frame: dict, target) -> tuple[dict, memoryview]: needs_init |= {args[i]["buffer"] for i in ins if "buffer" in args[i] and args[i]["buffer"] not in written} written |= {args[i]["buffer"] for i in outs if "buffer" in args[i]} - assert all(_buffer(b) is not None for b, i in buffers.items() if i in needs_init), "a kernel reads a scratch before any kernel writes it" + assert all(buffer(b) is not None for b, i in buffers.items() if i in needs_init), "a kernel reads a scratch before any kernel writes it" names = list(jit.captured.expected_names) inputs = [{"slot": slot, "name": names[slot] if slot < len(names) else None, "dtype": repr(u.dtype), "numel": int(u.max_numel()), "device": u.device} for slot, u in enumerate(_prepare_jit_inputs((), kwargs)[0])] header = {"input_names": names, "calls": calls, "returns": {"kind": "NoneType", "tensors": []}, "inputs": inputs, - "buffers": [{"nbytes": bb.nbytes if (bb := _buffer(b)) else b.max_numel() * b.dtype.itemsize, "device": bb.device if bb else b.device, "dtype": u8} + "buffers": [{"nbytes": bb.nbytes if (bb := buffer(b)) else b.max_numel() * b.dtype.itemsize, "device": bb.device if bb else b.device, "dtype": u8} | ({"init": blob.add(bb.ensure_allocated().as_memoryview())} if i in needs_init else {}) for b, i in buffers.items()], "check": {"inputs": [[path, store(array), device] for path, array, device in frame["inputs"]], "outputs": [store(array) for array in frame["outputs"]], "output_container": frame["output_container"]}} @@ -225,7 +240,6 @@ def main(): patch_fetch_fw() from examples.openpilot.helpers import allocate_inputs, load_pickle from tinygrad import Device, Tensor - from tinygrad.engine.realize import lower_and_compile artifact = load_pickle(args.pkl, out_of_band=True) artifact["run"].captured._linear = lower_and_compile(artifact["run"].captured._linear) rng = np.random.default_rng(7) diff --git a/openpilot/sunnypilot/modeld_v2/frame_fusion.py b/openpilot/sunnypilot/modeld_v2/frame_fusion.py index 9fe26199e1..3f518783f6 100644 --- a/openpilot/sunnypilot/modeld_v2/frame_fusion.py +++ b/openpilot/sunnypilot/modeld_v2/frame_fusion.py @@ -21,6 +21,13 @@ def pack_layout(shapes: dict[str, tuple], frame_size: int) -> tuple[dict[str, in offsets[name], offset = offset, offset + -(-math.prod(shape) * 4 // 128) * 128 return offsets | {"frames": offset}, offset + 2 * frame_size +EXTRA_WARPS = {"light_img": "light_tfm"} +SPLIT_FRAMES = ("big_frame", "frame") + +def host_shapes(input_shapes: dict[str, tuple], states) -> dict[str, tuple]: + shapes = {name: shape for name, shape in input_shapes.items() if name not in states and name != "new_img" and name not in EXTRA_WARPS} + return shapes | {tfm: (1, 3, 3) for img, tfm in EXTRA_WARPS.items() if img in input_shapes} + class _Blobs: # the model's and the warp's blobs as one address space, for a part whose ranges span both files def __init__(self, *blobs): @@ -32,31 +39,47 @@ class _Blobs: # the model's and the warp's blobs as one address space, for a pa def fused_with_warp(cam_w: int, cam_h: int, chestnut: bool): # load_model's extend: a native model runs upload, warp and model as one submit - return partial(frame_part, f"{BASEDIR}/openpilot/sunnypilot/modeld_v2/models/{'big_' if chestnut else ''}driving_warp_{cam_w}x{cam_h}_tinygrad.pkl") + models, big = f"{BASEDIR}/openpilot/sunnypilot/modeld_v2/models", 'big_' if chestnut else '' + return partial(frame_part, f"{models}/{big}driving_warp_{cam_w}x{cam_h}_tinygrad.pkl", + light_warp_path=f"{models}/{big}driving_lightwarp_{cam_w}x{cam_h}_tinygrad.pkl") -def frame_part(warp_path: str, parts: dict, extras: dict) -> dict: +def frame_part(warp_path: str, parts: dict, extras: dict, light_warp_path: str = "") -> dict: if "input_specs" not in extras: # a legacy model warps in its own parts return {} (model, model_blob), (warp, warp_blob) = parts["run"], read_parts(warp_path)[0]["run"] states = sorted(name for name in extras["input_specs"] if f"next_{name}" in extras["metadata"]["output_shapes"]) - host = {name: shape for name, (shape, _, _) in extras["input_specs"].items() if name not in states and name != "new_img"} - frame_specs = {s["name"]: s for s in warp["inputs"] if s["name"] in SPLIT_FRAMES} - offsets, packed = pack_layout(host, 0 if frame_specs else next(s["numel"] for s in warp["inputs"] if s["name"] == "input_frame") // 2) - shift, upload, u8 = len(model_blob), len(model["buffers"]) + len(warp["buffers"]), repr(_dtype("dtypes.uint8")) + host = host_shapes({name: shape for name, (shape, _, _) in extras["input_specs"].items()}, states) + paths = {"light_img": light_warp_path} + extra = [(img, tfm, *read_parts(paths[img])[0]["run"]) for img, tfm in EXTRA_WARPS.items() if img in extras["input_specs"]] + split = any(s["name"] in SPLIT_FRAMES for s in warp["inputs"]) + assert all(any(s["name"] in SPLIT_FRAMES for s in part["inputs"]) == split for _, _, part, _ in extra), "camera and extra warps must share a frame layout" + offsets, packed = pack_layout(host, 0 if split else next(s["numel"] for s in warp["inputs"] if s["name"] == "input_frame") // 2) + shift = len(model_blob) + buf_base, blob_base = [len(model["buffers"]) + len(warp["buffers"])], [len(model_blob) + len(warp_blob)] + for _, _, part, blob in extra: + buf_base.append(buf_base[-1] + len(part["buffers"])) + blob_base.append(blob_base[-1] + len(blob)) + upload, u8 = buf_base[-1], repr(_dtype("dtypes.uint8")) + extra_at = {img: (part, buf_base[i], blob_base[i], tfm) for i, (img, tfm, part, _) in enumerate(extra)} def view(name: str, nbytes: int, dtype: str) -> dict: return {"buffer": upload, "offset": offsets[name], "nbytes": nbytes, "dtype": dtype} outputs = sorted(s["slot"] for s in model["inputs"] if s["name"] is None) + frame_specs = {s["name"]: s for _, _, part, _ in [(None, None, warp, None), *extra] for s in part["inputs"] if s["name"] in SPLIT_FRAMES} names = sorted(["host", *states, *frame_specs]) slots = {s["slot"]: names.index(s["name"]) for s in model["inputs"] if s["name"] in states} | \ {slot: len(names) + i for i, slot in enumerate(outputs)} - returned = warp["returns"]["tensors"][0] + def warped(part: dict, base: int) -> dict: + returned = part["returns"]["tensors"][0] + return {k: v for k, v in returned.items() if k != "shape"} | {"buffer": returned["buffer"] + base} model_inputs = {s["slot"]: {"input": slots[s["slot"]]} if s["slot"] in slots else - {k: v for k, v in returned.items() if k != "shape"} | {"buffer": returned["buffer"] + len(model["buffers"])} if s["name"] == "new_img" else + warped(warp, len(model["buffers"])) if s["name"] == "new_img" else + warped(extra_at[s["name"]][0], extra_at[s["name"]][1]) if s["name"] in extra_at else view(s["name"], s["numel"] * _dtype(s["dtype"]).itemsize, s["dtype"]) for s in model["inputs"]} - warp_inputs = {s["slot"]: {"input": names.index(s["name"])} if s["name"] in frame_specs else - view("frames" if s["name"] == "input_frame" else "tfm", s["numel"] * _dtype(s["dtype"]).itemsize, s["dtype"]) for s in warp["inputs"]} + def warp_inputs(part: dict, tfm: str) -> dict: + return {s["slot"]: {"input": names.index(s["name"])} if s["name"] in frame_specs else + view("frames" if s["name"] == "input_frame" else tfm, s["numel"] * _dtype(s["dtype"]).itemsize, s["dtype"]) for s in part["inputs"]} def remap(calls: list, inputs: dict, buffers: int, lib: int) -> list: return [call | ({"lib": [call["lib"][0] + lib, call["lib"][1] + lib]} if "lib" in call else {}) | @@ -65,8 +88,11 @@ def frame_part(warp_path: str, parts: dict, extras: dict) -> dict: "inputs": [{"slot": names.index("host"), "name": "host", "dtype": u8, "numel": packed, "device": "NPY"}] + [s | {"slot": slots[s["slot"]]} for s in model["inputs"] if s["slot"] in slots] + [s | {"slot": names.index(name)} for name, s in frame_specs.items()], - "buffers": model["buffers"] + [b | ({"init": [b["init"][0] + shift, b["init"][1] + shift]} if "init" in b else {}) for b in warp["buffers"]] + + "buffers": model["buffers"] + [b | ({"init": [b["init"][0] + d, b["init"][1] + d]} if "init" in b else {}) + for part, d in ((warp, shift), *((p, bb) for p, _, bb, _ in extra_at.values())) for b in part["buffers"]] + [{"nbytes": packed, "device": model["inputs"][0]["device"], "dtype": u8}], "calls": [{"kind": "copy", "args": [{"buffer": upload, "offset": 0, "nbytes": packed, "dtype": u8}, {"input": names.index("host")}]}] + - remap(warp["calls"], warp_inputs, len(model["buffers"]), shift) + remap(model["calls"], model_inputs, 0, 0)} - return {"run": (header, _Blobs(model_blob, warp_blob))} # replaces the model's run: one set of buffers, no separate warp + remap(warp["calls"], warp_inputs(warp, "tfm"), len(model["buffers"]), shift) + + [c for p, b0, bb, tfm in extra_at.values() for c in remap(p["calls"], warp_inputs(p, tfm), b0, bb)] + + remap(model["calls"], model_inputs, 0, 0)} + return {"run": (header, _Blobs(model_blob, warp_blob, *(blob for *_, blob in extra)))} diff --git a/openpilot/sunnypilot/modeld_v2/helpers.py b/openpilot/sunnypilot/modeld_v2/helpers.py index 9a4434a35b..85154dfb9a 100644 --- a/openpilot/sunnypilot/modeld_v2/helpers.py +++ b/openpilot/sunnypilot/modeld_v2/helpers.py @@ -5,6 +5,7 @@ This file is part of sunnypilot and is licensed under the MIT License. See the LICENSE.md file in the root directory for more details. """ +import inspect import bisect import builtins import contextlib @@ -332,11 +333,13 @@ class PlainJit(_Jit): stand_ins = {slot: UOp.from_buffer(Buffer(_device(spec["device"], device_map), spec["numel"] * _dtype(spec["dtype"]).itemsize).ensure_allocated(), _dtype(spec["dtype"])) for slot, spec in inputs.items()} input_uops = tuple(stand_ins.get(slot, next(iter(stand_ins.values()), None)) for slot in range(max(stand_ins, default=-1) + 1)) - linear = jit.compile_linear(UOp(Ops.LINEAR, src=tuple(calls)), beam=0, input_uops=input_uops, cache=False) + takes_inputs = "input_uops" in inspect.signature(jit.compile_linear).parameters + linear = jit.compile_linear(UOp(Ops.LINEAR, src=tuple(calls)), beam=0, cache=False, **({"input_uops": input_uops} if takes_inputs else {})) returned = [Tensor(argument(t)).reshape(tuple(t["shape"])) for t in header["returns"]["tensors"]] ret = {"NoneType": None, "Tensor": returned[0] if returned else None, "tuple": tuple(returned), "list": returned}[header["returns"]["kind"]] - super().__init__(jit.CapturedJit(ret, linear, header["input_names"], []), header["input_names"], buffers) + captured = jit.CapturedJit(ret, linear, header["input_names"], []) if takes_inputs else jit.CapturedJit(ret, linear, (), header["input_names"], [], {}) + super().__init__(captured, header["input_names"], buffers) if not verify or not (check := header.get("check")): return diff --git a/openpilot/sunnypilot/modeld_v2/light_frame.py b/openpilot/sunnypilot/modeld_v2/light_frame.py new file mode 100644 index 0000000000..730b428ae7 --- /dev/null +++ b/openpilot/sunnypilot/modeld_v2/light_frame.py @@ -0,0 +1,22 @@ +""" +Copyright (c) 2021-, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import numpy as np + +from openpilot.common.transformations.camera import get_view_frame_from_calib_frame, view_frame_from_device_frame +from openpilot.common.transformations.orientation import rot_from_euler + +LIGHT_INPUT_SIZE = (512, 256) +light_intrinsics = np.array([ + [1000.0, 0.0, 256.0], + [0.0, 1000.0, 200.0], + [0.0, 0.0, 1.0]]) +calib_from_light = np.linalg.inv((light_intrinsics @ get_view_frame_from_calib_frame(0, 0, 0, 0))[:, :3]) + + +def get_light_warp_matrix(device_from_calib_euler: np.ndarray, intrinsics: np.ndarray) -> np.ndarray: + camera_from_calib = intrinsics @ view_frame_from_device_frame @ rot_from_euler(device_from_calib_euler) + return (camera_from_calib @ calib_from_light).astype(np.float32) diff --git a/openpilot/sunnypilot/modeld_v2/model_adapters.py b/openpilot/sunnypilot/modeld_v2/model_adapters.py index fc6ee0d83c..8e5b1597de 100644 --- a/openpilot/sunnypilot/modeld_v2/model_adapters.py +++ b/openpilot/sunnypilot/modeld_v2/model_adapters.py @@ -11,7 +11,7 @@ import pickle import numpy as np from openpilot.common.basedir import BASEDIR -from openpilot.sunnypilot.modeld_v2.frame_fusion import pack_layout, SPLIT_FRAMES +from openpilot.sunnypilot.modeld_v2.frame_fusion import host_shapes, pack_layout, SPLIT_FRAMES from openpilot.sunnypilot.modeld_v2.helpers import load_model from openpilot.sunnypilot.modeld_v2.compile_modeld import (POLICY_INPUTS, derive_frame_skip, make_split_input_queues, make_supercombo_input_queues) @@ -174,7 +174,7 @@ class NativeTinygradAdapter(BaseModelAdapter): self.input_queues = {name: Tensor(np.zeros(shape, dtype=dtype), device=self.model_device).realize() for name, (shape, dtype) in self.input_shapes.items() if name in self.state_pairs} - shapes = {name: shape for name, (shape, _) in self.input_shapes.items() if name not in self.state_pairs and name != 'new_img'} + shapes = host_shapes({name: shape for name, (shape, _) in self.input_shapes.items()}, self.state_pairs) offsets, packed = pack_layout(shapes, 0 if self.split else self.warp_frame_size) self.packed_input = np.zeros(packed, dtype=np.uint8) self.host = Tensor(self.packed_input, device='NPY') diff --git a/openpilot/sunnypilot/modeld_v2/modeld.py b/openpilot/sunnypilot/modeld_v2/modeld.py index 7c4ccd791b..644a3b4f9a 100755 --- a/openpilot/sunnypilot/modeld_v2/modeld.py +++ b/openpilot/sunnypilot/modeld_v2/modeld.py @@ -44,6 +44,7 @@ from openpilot.sunnypilot.modeld_v2.blendful import Blendful from openpilot.sunnypilot.modeld_v2.constants import ModelConstants, Plan from openpilot.sunnypilot.modeld_v2.meta_helper import load_meta_constants from openpilot.sunnypilot.modeld_v2.camera_offset_helper import CameraOffsetHelper +from openpilot.sunnypilot.modeld_v2.light_frame import get_light_warp_matrix from openpilot.sunnypilot.livedelay.helpers import get_lat_delay from openpilot.sunnypilot.modeld_v2.modeld_base import ModelStateBase from openpilot.sunnypilot.modeld_v2.helpers import load_model @@ -171,7 +172,7 @@ class ModelState(ModelStateBase): np.where(inputs[desire_key] - self.prev_desire > .99, inputs[desire_key], 0) self.prev_desire[:] = inputs[desire_key] - for key in ('traffic_convention', 'lateral_control_params', 'action_t'): + for key in ('traffic_convention', 'lateral_control_params', 'action_t', 'speed_limit'): if key in self.numpy_inputs and key in inputs: self.numpy_inputs[key][:] = inputs[key] @@ -179,6 +180,8 @@ class ModelState(ModelStateBase): for i, key in enumerate(self._vision_input_names): if key in transforms: self.numpy_inputs['tfm'][i] = transforms[key].reshape(3, 3) + if 'light_tfm' in self.numpy_inputs and 'light' in transforms: + self.numpy_inputs['light_tfm'][0] = transforms['light'].reshape(3, 3) else: self.numpy_inputs['tfm'][:, :] = transforms[self._road_key].reshape(3, 3) self.numpy_inputs['big_tfm'][:, :] = transforms[self._wide_key].reshape(3, 3) @@ -353,6 +356,7 @@ def main(demo=False): model_transform_main = np.zeros((3, 3), dtype=np.float32) model_transform_extra = np.zeros((3, 3), dtype=np.float32) + model_transform_light = np.zeros((3, 3), dtype=np.float32) live_calib_seen = False buf_main, buf_extra = None, None meta_main = FrameMeta() @@ -371,6 +375,9 @@ def main(demo=False): prev_action = log.ModelDataV2.Action() DH = DesireHelper() + desire_frames = [q.shape[0] for m in (model, small_model) if m is not None for name, q in m.adapter.input_queues.items() if 'desire' in name] + if desire_frames: + DH.turn_repulse = min(desire_frames) - 2 meta_constants = load_meta_constants() RELC = RoadEdgeLaneChangeController() blendful = Blendful() @@ -427,6 +434,7 @@ def main(demo=False): model_transform_main = get_warp_matrix(device_from_calib_euler, main_intrinsics, False).astype(np.float32) model_transform_extra = get_warp_matrix(device_from_calib_euler, dc.wide_road.intrinsics, True).astype(np.float32) model_transform_main, model_transform_extra = camera_offset_helper.update(model_transform_main, model_transform_extra, sm, main_wide_camera) + model_transform_light = get_light_warp_matrix(device_from_calib_euler, main_intrinsics) live_calib_seen = True traffic_convention = np.zeros(2) @@ -448,6 +456,7 @@ def main(demo=False): bufs = {name: buf_extra if 'big' in name else buf_main for name in model.vision_input_names} transforms = {name: model_transform_extra if 'big' in name else model_transform_main for name in model.vision_input_names} + transforms['light'] = model_transform_light frame_delay = DT_MDL # compensate for time passed since the frame was captured: current_time - timestamp_eof is 50ms on average action_delay = DT_MDL / 2 # middle of the interval between model output (current state) and next frame (expected state) @@ -465,6 +474,9 @@ def main(demo=False): if 'action_t' in model.numpy_inputs: inputs['action_t'] = np.array([lat_action_t, long_action_t], dtype=np.float32) + if 'speed_limit' in model.numpy_inputs: + inputs['speed_limit'] = np.zeros(1, dtype=np.float32) + mt1 = time.perf_counter() try: send_chestnut = (chestnut_state is not None and diff --git a/openpilot/sunnypilot/modeld_v2/models/big_driving_lightwarp_1344x760_tinygrad.pkl b/openpilot/sunnypilot/modeld_v2/models/big_driving_lightwarp_1344x760_tinygrad.pkl new file mode 100644 index 0000000000..fdb8882d29 --- /dev/null +++ b/openpilot/sunnypilot/modeld_v2/models/big_driving_lightwarp_1344x760_tinygrad.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1baac6f02902df5689e9e275633c122a9955b7c57de2681e0137e1724c1f32dd +size 3463278 diff --git a/openpilot/sunnypilot/modeld_v2/models/big_driving_lightwarp_1928x1208_tinygrad.pkl b/openpilot/sunnypilot/modeld_v2/models/big_driving_lightwarp_1928x1208_tinygrad.pkl new file mode 100644 index 0000000000..477bb31b83 --- /dev/null +++ b/openpilot/sunnypilot/modeld_v2/models/big_driving_lightwarp_1928x1208_tinygrad.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0478837491c584b2212e31a91c494a908b8fb048205700f05a02a13ee7fc9b90 +size 7690094 diff --git a/openpilot/sunnypilot/modeld_v2/models/driving_lightwarp_1344x760_tinygrad.pkl b/openpilot/sunnypilot/modeld_v2/models/driving_lightwarp_1344x760_tinygrad.pkl new file mode 100644 index 0000000000..19e7e39842 --- /dev/null +++ b/openpilot/sunnypilot/modeld_v2/models/driving_lightwarp_1344x760_tinygrad.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:580fadf61ded34b4b19f0ba1f5e4b61c0ea489ca34a0952ccf2878593e3f68c4 +size 1851239 diff --git a/openpilot/sunnypilot/modeld_v2/models/driving_lightwarp_1928x1208_tinygrad.pkl b/openpilot/sunnypilot/modeld_v2/models/driving_lightwarp_1928x1208_tinygrad.pkl new file mode 100644 index 0000000000..b1126a07c1 --- /dev/null +++ b/openpilot/sunnypilot/modeld_v2/models/driving_lightwarp_1928x1208_tinygrad.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:44700f3533abb3e65232c8aca46b48384a59218545ed6bb505c5d4762204359b +size 3964263 diff --git a/openpilot/sunnypilot/modeld_v2/tests/test_convert_upstream_pkl.py b/openpilot/sunnypilot/modeld_v2/tests/test_convert_upstream_pkl.py index c9c61d773a..7313e50064 100644 --- a/openpilot/sunnypilot/modeld_v2/tests/test_convert_upstream_pkl.py +++ b/openpilot/sunnypilot/modeld_v2/tests/test_convert_upstream_pkl.py @@ -90,7 +90,7 @@ class TestConvertUpstreamPkl(OpenpilotTestCase): kwargs = self.inputs(2) frame, _ = capture_frame(jit, kwargs, "output_buffers") header, blob = convert(jit, kwargs, frame, Device[Device.DEFAULT].renderer.target) - kernels = jit.captured._linear.src[0].without_after.arg.aux.kernels + kernels = convert_upstream_pkl.submit_kernels(jit) assert [call["name"] for call in header["calls"]] == [re.sub(r"\x1b\[[0-9;]*m", "", kernel[1]) for kernel in kernels] assert all(re.fullmatch(r"\w+", call["name"]) for call in header["calls"]), "kernel names: failure point 1" assert [(tuple(call["outs"]), tuple(call["ins"])) for call in header["calls"]] == [tuple(kernel[6]) for kernel in kernels], "outs/ins: failure point 1" @@ -107,12 +107,11 @@ class TestConvertUpstreamPkl(OpenpilotTestCase): def test_pickle_round_trip_through_main(self): from examples.openpilot.helpers import dump_pickle, load_pickle - from tinygrad.engine.realize import lower_and_compile pkl, out = os.path.join(self.tmp.name, "tiny_tinygrad.pkl"), os.path.join(self.tmp.name, "tiny_plain.pkl") dump_pickle({"run": self.jit(), "input_specs": self.input_specs, "output_specs": self.output_specs, "metadata": {"name": "tiny"}}, pkl) artifact = load_pickle(pkl, out_of_band=True) - artifact["run"].captured._linear = lower_and_compile(artifact["run"].captured._linear) + artifact["run"].captured._linear = convert_upstream_pkl.lower_and_compile(artifact["run"].captured._linear) self.assert_matches_eager(PlainJit(*self.convert(artifact["run"])), 5) with mock.patch.object(sys, "argv", ["convert_upstream_pkl", pkl, out]): diff --git a/tinygrad_repo b/tinygrad_repo index f8a103318f..3589d75d74 160000 --- a/tinygrad_repo +++ b/tinygrad_repo @@ -1 +1 @@ -Subproject commit f8a103318fbeb3c1b42e843bc03247485c50cdc7 +Subproject commit 3589d75d7402a3a73f51c867056681cd9b803018