

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 搭配 @remote 裝飾項目使用模組化代碼
<a name="train-remote-decorator-modular"></a>

您可以將代碼組織為模組，以便於開發期間進行工作區管理，且仍可使用 @remote 函式來調用函式。您還可以將本機模組從開發環境複寫到遠端工作環境。若要這麼做，請設定參數 `include_local_workdir` 為 `True`，如下列代碼範例所示。

```
@remote(
  include_local_workdir=True,
)
```

**注意**  
@remote 裝飾項目與參數必須出現在主檔案，而非在任何相依檔案。

當設定 `include_local_workdir` 為 `True` 時，SageMaker AI 會封裝所有 Python 指令碼，同時維護處理程序目前目錄的目錄結構。其也會讓相依性可用於工作的工作目錄。

例如，假設處理 MNIST 資料集的 Python 指令碼分為 `main.py` 指令碼和相依 `pytorch_mnist.py` 指令碼。`main.py` 會呼叫相依指令碼。此外，`main.py` 指令碼包含用於匯入相依性的程式碼，如下所示。

```
from mnist_impl.pytorch_mnist import ...
```

`main.py` 檔案也必須包含 `@remote` 裝飾項目，且其必須將 `include_local_workdir` 參數設為 `True`。

根據預設，`include_local_workdir` 參數包含目錄中的所有 Python 指令碼。您可以使用此參數搭配 `custom_file_filter` 參數，自訂要上傳至任務的檔案。您可以傳遞篩選要上傳至 S3 的任務相依性的函式，或傳遞指定遠端函式要忽略的本機目錄和檔案的 `CustomFileFilter` 物件。您只能在 `include_local_workdir` 設為 `True` 時使用 `custom_file_filter`，否則參數會遭忽略。

下列範例使用 `CustomFileFilter`，在將檔案上傳至 S3 時，忽略所有筆記本檔案和名為 `data` 的資料夾或檔案。

```
@remote(
   include_local_workdir=True,
   custom_file_filter=CustomFileFilter(
      ignore_name_patterns=[ # files or directories to ignore
        "*.ipynb", # all notebook files
        "data", # folter or file named data
      ]
   )
)
```

下列範例說明如何封裝整個工作區。

```
@remote(
   include_local_workdir=True,
   custom_file_filter=CustomFileFilter(
      ignore_pattern_names=[] # package whole workspace
   )
)
```

下列範例說明如何使用函式來篩選檔案。

```
import os

def my_filter(path: str, files: List[str]) -> List[str]:
    to_ignore = []
   for file in files:
       if file.endswith(".txt") or file.endswith(".ipynb"):
           to_ignore.append(file)
   return to_ignore

@remote(
   include_local_workdir=True,
   custom_file_filter=my_filter
)
```

## 建構工作目錄最佳實務
<a name="train-remote-decorator-modular-bestprac"></a>

下列最佳實務說明如何在模組化程式碼中使用 `@remote` 裝飾項目時，組織目錄結構。
+ 將 @remote 裝飾項目放在位於工作區根層級目錄的檔案。
+ 在根層級建構本機模組。

下列範例映像顯示建議的目錄結構。在此範例結構，`main.py` 指令碼位於根層級目錄。

```
.
├── config.yaml
├── data/
├── main.py <----------------- @remote used here 
├── mnist_impl
│ ├── __pycache__/
│ │ └── pytorch_mnist.cpython-310.pyc
│ ├── pytorch_mnist.py <-------- dependency of main.py
├── requirements.txt
```

下列範例映像顯示的目錄結構說明，當使用該目錄結構來運用 @remote 裝飾項目註釋代碼時，會導致行為不一致。

在此範例結構，包含 @remote 裝飾項目的 `main.py` 指令碼並**不**位於根層級目錄。**不**推薦採用以下結構。

```
.
├── config.yaml
├── entrypoint
│ ├── data
│ └── main.py <----------------- @remote used here
├── mnist_impl
│ ├── __pycache__
│ │ └── pytorch_mnist.cpython-310.pyc
│ └── pytorch_mnist.py <-------- dependency of main.py
├── requirements.txt
```