

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

# Gerenciar modelos
<a name="edge-manage-model"></a>

O agente do Edge Manager pode carregar vários modelos ao mesmo tempo e fazer inferências com modelos carregados em dispositivos de borda. O número de modelos que o agente pode carregar é determinado pela memória disponível no dispositivo. O agente valida a assinatura do modelo e carrega na memória todos os artefatos produzidos pelo trabalho de empacotamento do Edge. Essa etapa exige que todos os certificados necessários descritos nas etapas anteriores sejam instalados junto com o restante da instalação binária. Se a assinatura do modelo não puder ser validada, o carregamento do modelo falhará com o código de devolução e o motivo apropriados.

SageMaker O agente do Edge Manager fornece uma lista de APIs de gerenciamento de modelos que implementam APIs de plano de controle e plano de dados em dispositivos de borda. Junto com essa documentação, recomendamos examinar o exemplo de implementação do cliente, que mostra o uso canônico das APIs descritas abaixo.

O arquivo `proto` está disponível como parte dos artefatos de lançamento (dentro do pacote de lançamento). Neste documento, listamos e descrevemos o uso das APIs listadas neste arquivo `proto`.

**nota**  
Há um mapeamento individual para essas APIs na versão do Windows e um código de amostra para uma implementação de aplicação em C\# é compartilhado com os artefatos de versão do Windows. As instruções abaixo são para executar o agente como um processo independente, aplicável aos artefatos de lançamento para Linux.

Extraia o arquivo com base no seu sistema operacional. Onde o `VERSION` estiver quebrado em três componentes: `<MAJOR_VERSION>.<YYYY-MM-DD>-<SHA-7>`. Consulte [Instalando o agente do Edge Manager](edge-device-fleet-manual.md#edge-device-fleet-installation) para obter informações sobre como obter a versão de lançamento (`<MAJOR_VERSION>`), a data e hora do artefato de lançamento (`<YYYY-MM-DD>`) e o ID de confirmação do repositório (`SHA-7`)

------
#### [ Linux ]

O arquivo zip pode ser extraído com o comando:

```
tar -xvzf {{<VERSION>}}.tgz
```

------
#### [ Windows ]

O arquivo zip pode ser extraído com o interface do usuário ou o comando:

```
unzip {{<VERSION>}}.tgz
```

------

A hierarquia do artefato de lançamento (depois de extrair o arquivo `tar/zip`) é mostrada abaixo. O arquivo `proto` do agente está disponível em `api/`.

```
0.20201205.7ee4b0b
├── bin
│         ├── sagemaker_edge_agent_binary
│         └── sagemaker_edge_agent_client_example
└── docs
├── api
│         └── agent.proto
├── attributions
│         ├── agent.txt
│         └── core.txt
└── examples
└── ipc_example
├── CMakeLists.txt
├── sagemaker_edge_client.cc
├── sagemaker_edge_client_example.cc
├── sagemaker_edge_client.hh
├── sagemaker_edge.proto
├── README.md
├── shm.cc
├── shm.hh
└── street_small.bmp
```

**Topics**
+ [Carregar modelo](#edge-manage-model-loadmodel)
+ [Descarregar modelo](#edge-manage-model-unloadmodel)
+ [Listar modelos](#edge-manage-model-listmodels)
+ [Descrever modelo](#edge-manage-model-describemodel)
+ [Capturar dados](#edge-manage-model-capturedata)
+ [Obter status de captura](#edge-manage-model-getcapturedata)
+ [Prever](#edge-manage-model-predict)

## Carregar modelo
<a name="edge-manage-model-loadmodel"></a>

O agente do Edge Manager é compatível com o carregamento de vários modelos. Essa API valida a assinatura do modelo e carrega na memória todos os artefatos produzidos pela operação `EdgePackagingJob`. Esta etapa requer que todos os certificados necessários sejam instalados junto com o restante da instalação binária do agente. Se a assinatura do modelo não puder ser validada, esta etapa falhará com o código de retorno apropriado e mensagens de erro no log.

```
// perform load for a model
// Note:
// 1. currently only local filesystem paths are supported for loading models.
// 2. multiple models can be loaded at the same time, as limited by available device memory
// 3. users are required to unload any loaded model to load another model.
// Status Codes:
// 1. OK - load is successful
// 2. UNKNOWN - unknown error has occurred
// 3. INTERNAL - an internal error has occurred
// 4. NOT_FOUND - model doesn't exist at the url
// 5. ALREADY_EXISTS - model with the same name is already loaded
// 6. RESOURCE_EXHAUSTED - memory is not available to load the model
// 7. FAILED_PRECONDITION - model is not compiled for the machine.
//
rpc LoadModel(LoadModelRequest) returns (LoadModelResponse);
```

------
#### [ Input ]

```
//
// request for LoadModel rpc call
//
message LoadModelRequest {
  string url = 1;
  string name = 2;  // Model name needs to match regex "^[a-zA-Z0-9](-*[a-zA-Z0-9])*$"
}
```

------
#### [ Output ]

```
//
//
// response for LoadModel rpc call
//
message LoadModelResponse {
  Model model = 1;
}

//
// Model represents the metadata of a model
//  url - url representing the path of the model
//  name - name of model
//  input_tensor_metadatas - TensorMetadata array for the input tensors
//  output_tensor_metadatas - TensorMetadata array for the output tensors
//
// Note:
//  1. input and output tensor metadata could empty for dynamic models.
//
message Model {
  string url = 1;
  string name = 2;
  repeated TensorMetadata input_tensor_metadatas = 3;
  repeated TensorMetadata output_tensor_metadatas = 4;
}
```

------

## Descarregar modelo
<a name="edge-manage-model-unloadmodel"></a>

Descarrega um modelo carregado anteriormente. É identificado por meio do alias do modelo fornecido durante `loadModel`. Se o alias não for encontrado ou o modelo não estiver carregado, retornará um erro.

```
//
// perform unload for a model
// Status Codes:
// 1. OK - unload is successful
// 2. UNKNOWN - unknown error has occurred
// 3. INTERNAL - an internal error has occurred
// 4. NOT_FOUND - model doesn't exist
//
rpc UnLoadModel(UnLoadModelRequest) returns (UnLoadModelResponse);
```

------
#### [ Input ]

```
//
// request for UnLoadModel rpc call
//
message UnLoadModelRequest {
 string name = 1; // Model name needs to match regex "^[a-zA-Z0-9](-*[a-zA-Z0-9])*$"
}
```

------
#### [ Output ]

```
//
// response for UnLoadModel rpc call
//
message UnLoadModelResponse {}
```

------

## Listar modelos
<a name="edge-manage-model-listmodels"></a>

Lista todos os modelos carregados e seus aliases.

```
//
// lists the loaded models
// Status Codes:
// 1. OK - unload is successful
// 2. UNKNOWN - unknown error has occurred
// 3. INTERNAL - an internal error has occurred
//
rpc ListModels(ListModelsRequest) returns (ListModelsResponse);
```

------
#### [ Input ]

```
//
// request for ListModels rpc call
//
message ListModelsRequest {}
```

------
#### [ Output ]

```
//
// response for ListModels rpc call
//
message ListModelsResponse {
 repeated Model models = 1;
}
```

------

## Descrever modelo
<a name="edge-manage-model-describemodel"></a>

Descreve um modelo que é carregado no agente.

```
//
// Status Codes:
// 1. OK - load is successful
// 2. UNKNOWN - unknown error has occurred
// 3. INTERNAL - an internal error has occurred
// 4. NOT_FOUND - model doesn't exist at the url
//
rpc DescribeModel(DescribeModelRequest) returns (DescribeModelResponse);
```

------
#### [ Input ]

```
//
// request for DescribeModel rpc call
//
message DescribeModelRequest {
  string name = 1;
}
```

------
#### [ Output ]

```
//
// response for DescribeModel rpc call
//
message DescribeModelResponse {
  Model model = 1;
}
```

------

## Capturar dados
<a name="edge-manage-model-capturedata"></a>

Permite que a aplicação cliente capture tensores de entrada e saída no bucket do Amazon S3 e, opcionalmente, no auxiliar. Espera-se que a aplicação do cliente transmita uma ID de captura exclusiva junto com cada chamada para essa API. Isso pode ser usado posteriormente para consultar o status da captura.

```
//
// allows users to capture input and output tensors along with auxiliary data.
// Status Codes:
// 1. OK - data capture successfully initiated
// 2. UNKNOWN - unknown error has occurred
// 3. INTERNAL - an internal error has occurred
// 5. ALREADY_EXISTS - capture initiated for the given capture_id
// 6. RESOURCE_EXHAUSTED - buffer is full cannot accept any more requests.
// 7. OUT_OF_RANGE - timestamp is in the future.
// 8. INVALID_ARGUMENT - capture_id is not of expected format.
//
rpc CaptureData(CaptureDataRequest) returns (CaptureDataResponse);
```

------
#### [ Input ]

```
enum Encoding {
 CSV = 0;
 JSON = 1;
 NONE = 2;
 BASE64 = 3;
}

//
// AuxilaryData represents a payload of extra data to be capture along with inputs and outputs of inference
// encoding - supports the encoding of the data
// data - represents the data of shared memory, this could be passed in two ways:
// a. send across the raw bytes of the multi-dimensional tensor array
// b. send a SharedMemoryHandle which contains the posix shared memory segment id and
// offset in bytes to location of multi-dimensional tensor array.
//
message AuxilaryData {
 string name = 1;
 Encoding encoding = 2;
 oneof data {
 bytes byte_data = 3;
 SharedMemoryHandle shared_memory_handle = 4;
 }
}

//
// Tensor represents a tensor, encoded as contiguous multi-dimensional array.
// tensor_metadata - represents metadata of the shared memory segment
// data_or_handle - represents the data of shared memory, this could be passed in two ways:
// a. send across the raw bytes of the multi-dimensional tensor array
// b. send a SharedMemoryHandle which contains the posix shared memory segment
// id and offset in bytes to location of multi-dimensional tensor array.
//
message Tensor {
 TensorMetadata tensor_metadata = 1; //optional in the predict request
 oneof data {
 bytes byte_data = 4;
 // will only be used for input tensors
 SharedMemoryHandle shared_memory_handle = 5;
 }
}

//
// request for CaptureData rpc call
//
message CaptureDataRequest {
 string model_name = 1;
 string capture_id = 2; //uuid string
 Timestamp inference_timestamp = 3;
 repeated Tensor input_tensors = 4;
 repeated Tensor output_tensors = 5;
 repeated AuxilaryData inputs = 6;
 repeated AuxilaryData outputs = 7;
}
```

------
#### [ Output ]

```
//
// response for CaptureData rpc call
//
message CaptureDataResponse {}
```

------

## Obter status de captura
<a name="edge-manage-model-getcapturedata"></a>

Dependendo dos modelos carregados, os tensores de entrada e saída podem ser grandes (para muitos dispositivos de borda). A captura na nuvem pode ser demorada. Portanto, `CaptureData()` é implementado como uma operação assíncrona. Uma ID de captura é um identificador exclusivo que o cliente fornece durante a chamada de dados de captura. Essa ID pode ser usada para consultar o status da chamada assíncrona.

```
//
// allows users to query status of capture data operation
// Status Codes:
// 1. OK - data capture successfully initiated
// 2. UNKNOWN - unknown error has occurred
// 3. INTERNAL - an internal error has occurred
// 4. NOT_FOUND - given capture id doesn't exist.
//
rpc GetCaptureDataStatus(GetCaptureDataStatusRequest) returns (GetCaptureDataStatusResponse);
```

------
#### [ Input ]

```
//
// request for GetCaptureDataStatus rpc call
//
message GetCaptureDataStatusRequest {
  string capture_id = 1;
}
```

------
#### [ Output ]

```
enum CaptureDataStatus {
  FAILURE = 0;
  SUCCESS = 1;
  IN_PROGRESS = 2;
  NOT_FOUND = 3;
}

//
// response for GetCaptureDataStatus rpc call
//
message GetCaptureDataStatusResponse {
  CaptureDataStatus status = 1;
}
```

------

## Prever
<a name="edge-manage-model-predict"></a>

A API `predict` realiza inferência em um modelo carregado anteriormente. Aceita uma solicitação na forma de um tensor que é alimentado diretamente na rede neural. A saída é o tensor de saída (ou escalar) do modelo. Essa é uma chamada de bloqueio.

```
//
// perform inference on a model.
//
// Note:
// 1. users can chose to send the tensor data in the protobuf message or
// through a shared memory segment on a per tensor basis, the Predict
// method with handle the decode transparently.
// 2. serializing large tensors into the protobuf message can be quite expensive,
// based on our measurements it is recommended to use shared memory of
// tenors larger than 256KB.
// 3. SMEdge IPC server will not use shared memory for returning output tensors,
// i.e., the output tensor data will always send in byte form encoded
// in the tensors of PredictResponse.
// 4. currently SMEdge IPC server cannot handle concurrent predict calls, all
// these call will be serialized under the hood. this shall be addressed
// in a later release.
// Status Codes:
// 1. OK - prediction is successful
// 2. UNKNOWN - unknown error has occurred
// 3. INTERNAL - an internal error has occurred
// 4. NOT_FOUND - when model not found
// 5. INVALID_ARGUMENT - when tenors types mismatch
//
rpc Predict(PredictRequest) returns (PredictResponse);
```

------
#### [ Input ]

```
// request for Predict rpc call
//
message PredictRequest {
string name = 1;
repeated Tensor tensors = 2;
}

//
// Tensor represents a tensor, encoded as contiguous multi-dimensional array.
//    tensor_metadata - represents metadata of the shared memory segment
//    data_or_handle - represents the data of shared memory, this could be passed in two ways:
//                        a. send across the raw bytes of the multi-dimensional tensor array
//                        b. send a SharedMemoryHandle which contains the posix shared memory segment
//                            id and offset in bytes to location of multi-dimensional tensor array.
//
message Tensor {
  TensorMetadata tensor_metadata = 1; //optional in the predict request
  oneof data {
    bytes byte_data = 4;
    // will only be used for input tensors
    SharedMemoryHandle shared_memory_handle = 5;
  }
}

//
// Tensor represents a tensor, encoded as contiguous multi-dimensional array.
//    tensor_metadata - represents metadata of the shared memory segment
//    data_or_handle - represents the data of shared memory, this could be passed in two ways:
//                        a. send across the raw bytes of the multi-dimensional tensor array
//                        b. send a SharedMemoryHandle which contains the posix shared memory segment
//                            id and offset in bytes to location of multi-dimensional tensor array.
//
message Tensor {
  TensorMetadata tensor_metadata = 1; //optional in the predict request
  oneof data {
    bytes byte_data = 4;
    // will only be used for input tensors
    SharedMemoryHandle shared_memory_handle = 5;
  }
}

//
// TensorMetadata represents the metadata for a tensor
//    name - name of the tensor
//    data_type  - data type of the tensor
//    shape - array of dimensions of the tensor
//
message TensorMetadata {
  string name = 1;
  DataType data_type = 2;
  repeated int32 shape = 3;
}

//
// SharedMemoryHandle represents a posix shared memory segment
//    offset - offset in bytes from the start of the shared memory segment.
//    segment_id - shared memory segment id corresponding to the posix shared memory segment.
//    size - size in bytes of shared memory segment to use from the offset position.
//
message SharedMemoryHandle {
  uint64 size = 1;
  uint64 offset = 2;
  uint64 segment_id = 3;
}
```

------
#### [ Output ]

**nota**  
O `PredictResponse` somente retorna `Tensors` e não `SharedMemoryHandle`.

```
// response for Predict rpc call
//
message PredictResponse {
   repeated Tensor tensors = 1;
}
```

------