1. 소개
웹 신경망 API는 플랫폼별 기능에 종속되지 않으면서 운영 체제와 기반 하드웨어 플랫폼의 머신 러닝 기능을 활용하는 웹 친화적인 하드웨어 독립적 추상화 계층을 정의합니다. 이 추상화 계층은 주요 머신 러닝 JavaScript 프레임워크의 요구 사항을 충족하며, ML 분야에 익숙한 웹 개발자가 라이브러리의 도움 없이 사용자 정의 코드를 작성할 수도 있도록 합니다.
그림이 포함된 소개는 설명 문서를 참조하십시오.
2. 사용 사례
2.1. 애플리케이션 사용 사례
이 섹션에서는 신경망 추론 하드웨어 가속의 애플리케이션 수준 사용 사례를 설명합니다. 이러한 사용 사례의 모든 애플리케이션은 사전 학습된 심층 신경망(DNN) [models]을 기반으로 구축할 수 있습니다.
참고: 여기에 설명된 일부 사용 사례는 본질적으로 개인정보 침해 소지가 있음을 유의하십시오. 이러한 사용 사례에 API를 사용할 계획인 개발자는 API가 사용자가 이해하고 승인한 목적을 위해 사용자에게 이익이 되도록 사용되는지 확인해야 합니다. 또한 웹 머신 러닝을 위한 윤리 원칙 [webmachinelearning-ethics]을 적용하고 투명성, 데이터 최소화 및 사용자 제어와 같은 적절한 개인정보 보호 위험 완화 조치를 구현해야 합니다.
참고: § 3 접근성 고려 사항에서는 이러한 사용 사례의 접근성을 개선하는 방법에 대한 지침을 제공합니다.
2.1.1. 사람 감지
사용자가 웹 기반 화상 회의 애플리케이션을 열었지만 일시적으로 방을 떠납니다. 애플리케이션은 객체 감지(예를 들어, 단일 DNN을 사용하는 [SSD] 또는 [YOLO]와 같은 객체 감지 방식을 사용)를 통해 카메라 입력 프레임에서 사람이 포함된 영역을 감지하여 사용자가 PC 앞에 있는지 확인합니다.
사용자가 돌아오면 애플리케이션이 자동으로 사용자를 감지하고 다른 온라인 사용자에게 현재 활동 중임을 알립니다.
2.1.2. 의미론적 분할
사무실에 이용 가능한 회의실이 없어 사용자가 자신의 책상에서 웹 기반 화상 회의 애플리케이션을 통해 원격 회의에 참여합니다. 원격 회의 중 사용자는 자신의 방과 배경에 있는 사람들이 보이는 것을 원하지 않습니다. 다른 사람들과 주변 환경의 개인정보를 보호하기 위해 애플리케이션은 [DeepLabv3+], [MaskR-CNN] 또는 [SegAny]와 같은 머신 러닝 모델을 실행하여 이미지를 의미론적으로 여러 세그먼트로 분할하고, 다른 사람과 배경을 나타내는 세그먼트를 다른 이미지로 대체합니다.
2.1.3. 골격 감지
웹 기반 화상 회의 애플리케이션은 [PoseNet]과 같이 실시간 사람 자세 추정을 지원하는 머신 러닝 모델을 실행하여 사용자의 골격 자세를 추적하고 제스처와 몸짓을 인식합니다. 사용자가 손을 들면 마이크의 음소거가 자동으로 해제되어 원격 회의에서 발언을 시작할 수 있습니다.
2.1.4. 얼굴 인식
회의실에 여러 사람이 있으며 웹 기반 화상 회의 애플리케이션을 사용하여 온라인 회의에 참여합니다. 애플리케이션은 객체 감지(예를 들어, [SSD]와 같은 객체 감지 방식)를 사용하여 참가자의 얼굴을 감지하고, [FaceNet]과 같은 머신 러닝 모델을 실행하여 두 얼굴이 동일한지 검증함으로써 각 얼굴이 이전 회의에 있었는지 여부를 확인합니다.
2.1.5. 얼굴 랜드마크 감지
사용자가 온라인 안경 매장에서 자신에게 잘 어울리는 새 안경을 찾으려고 합니다. 온라인 매장은 Face Alignment Network [FAN]과 같은 머신 러닝 모델을 실행하여 눈, 코, 입 등의 얼굴 랜드마크를 감지하는 웹 기반 착용 시뮬레이터를 제공합니다. 사용자가 안경을 선택하면 시뮬레이터는 얼굴 이미지에서 감지된 눈 위치에 선택한 안경을 적절하게 렌더링합니다.
2.1.6. 스타일 전이
사용자가 온라인 매장에서 화장품을 찾으며 어떤 색상이 자신의 얼굴에 어울릴지 고민하고 있습니다. 온라인 매장은 화장품의 샘플 얼굴 메이크업 이미지를 보여주고, [ContextualLoss] 또는 [PairedCycleGAN]과 같은 머신 러닝 모델을 실행하여 샘플 메이크업 이미지의 메이크업 스타일을 사용자의 얼굴 이미지로 전이하는 메이크업 시뮬레이터를 제공합니다. 사용자는 시뮬레이터를 통해 선택한 메이크업이 자신의 얼굴에서 어떻게 보이는지 확인할 수 있습니다.
2.1.7. 초해상도
웹 기반 화상 회의 애플리케이션이 상대방으로부터 비디오 스트림을 수신하고 있지만, 네트워크 혼잡으로 인해 비디오 해상도가 낮아집니다. 인지되는 비디오 품질 저하를 방지하기 위해 애플리케이션은 [SRGAN]과 같은 초해상도 머신 러닝 모델을 실행하여 더 높은 해상도의 비디오 프레임을 생성합니다.
2.1.8. 이미지 캡셔닝
더 나은 접근성을 위해 웹 기반 프레젠테이션 애플리케이션은 프레젠테이션 슬라이드를 설명하는 단어를 예측하는 [im2txt]와 같은 머신 러닝 모델을 실행하여 자동 이미지 캡셔닝을 제공합니다.
2.1.9. 텍스트-이미지 변환
이미지는 현대 웹 경험의 핵심 요소입니다. 개인정보를 보호하는 방식으로 텍스트 입력을 기반으로 이미지를 생성하는 기능을 통해 웹 애플리케이션과 콘텐츠를 시각적으로 개인화하고 조정할 수 있습니다. 예를 들어 웹 애플리케이션은 웹 페이지의 자연어 설명이나 사용자가 텍스트 프롬프트에 제공한 설명을 입력으로 사용하여 해당 텍스트 설명과 일치하는 이미지를 생성할 수 있습니다. 잠재 확산 모델 아키텍처 [LDM]로 구현되는 이 텍스트-이미지 변환 사용 사례는 추가적인 텍스트-이미지 변환 사용 사례의 기반이 됩니다. 예를 들어 웹 페이지에 있는 기존 이미지의 일부를 새로 생성된 콘텐츠를 사용하여 선택적으로 수정하는 인페인팅이나, 그 반대인 아웃페인팅으로 원본 이미지를 원래 크기 너머로 확장하고 빈 공간을 생성된 콘텐츠로 채울 수 있습니다.
2.1.10. 기계 번역
여러 나라의 여러 사람이 웹 기반 실시간 텍스트 채팅 애플리케이션을 통해 대화하고 있습니다. 애플리케이션은 모든 텍스트를 다른 언어로 번역하는 [GNMT] 또는 [OpenNMT]와 같은 머신 러닝 모델을 사용하여 이들의 대화를 번역합니다.
2.1.11. 감정 분석
사용자가 웹 기반 실시간 텍스트 채팅 애플리케이션을 통해 친구와 대화하고 있는데, 친구의 얼굴을 볼 수 없어 친구가 어떻게 느끼는지 궁금해합니다. 애플리케이션은 입력 텍스트에서 감정을 추론하는 [DeepMoji]와 같은 머신 러닝 모델을 사용하여 친구의 감정을 분석하고, 추정된 감정을 나타내는 이모지를 표시합니다.
2.1.12. 비디오 요약
웹 기반 화상 회의 애플리케이션이 수신한 비디오 스트림을 녹화하며, 저장해야 하는 녹화 비디오 데이터의 양을 줄여야 합니다. 애플리케이션은 [Video-Summarization-with-LSTM]과 같은 비디오 요약용 머신 러닝 모델을 사용하여 녹화 비디오의 짧은 버전을 생성합니다.
2.1.13. 노이즈 억제
웹 기반 화상 회의 애플리케이션이 수신한 오디오 스트림을 녹음하지만, 일반적으로 배경 소음이 곳곳에 존재합니다. 애플리케이션은 [RNNoise]와 같은 순환 신경망을 사용한 실시간 노이즈 억제를 활용하여 아기 울음소리나 개 짖는 소리와 같은 동적인 배경 소음을 억제하고 화상 회의의 오디오 경험을 개선합니다.
2.1.14. 음성 인식
음성-텍스트 변환이라고도 하는 음성 인식은 말로 표현된 언어를 인식하고 텍스트로 변환할 수 있도록 합니다. 음성 인식 애플리케이션의 예로는 전사, 자동 번역, 다중 모달 상호작용, 실시간 자막 및 가상 비서가 있습니다. 음성 인식은 청각 콘텐츠의 접근성을 개선하고 개인정보를 보호하는 방식으로 이러한 콘텐츠와 텍스트 형태로 상호작용할 수 있도록 합니다. 일반적인 사용 사례의 예로는 실시간 자막을 사용하여 비디오를 시청하거나 온라인 회의에 참여하는 것이 있습니다. [Whisper]와 같은 모델은 정확성과 강건성 측면에서 인간 수준에 근접하며 이러한 사용 사례의 접근성을 개선하는 데 매우 적합합니다.
2.1.15. 텍스트 생성
텍스트 시퀀스의 다음 항목을 예측하는 일반적인 능력이 필요한 작업을 수행할 수 있는 대규모 언어 모델(LLM)을 통해 다양한 텍스트 생성 사용 사례를 구현할 수 있습니다. 이 유형의 모델은 텍스트를 번역하거나, 텍스트 입력을 기반으로 질문에 답하거나, 더 큰 분량의 텍스트를 요약하거나, 텍스트 입력을 기반으로 텍스트 출력을 생성할 수 있습니다. LLM은 RNN, CNN 또는 LSTM 아키텍처를 기반으로 한 이전 모델보다 더 나은 성능을 제공하며 이 섹션에서 설명하는 여러 다른 사용 사례의 성능도 더욱 개선합니다. LLM의 예로는 [t5-small], [m2m100_418M], [gpt2], 그리고 [llama-2-7b]가 있습니다.
2.1.16. 가짜 비디오 감지
사용자가 웹에서 ‘딥페이크’로 생성된 사실적인 가짜 비디오에 노출됩니다. 가짜 비디오는 화자의 얼굴을 대통령의 얼굴로 바꾸어 사용자를 정치적으로 선동하거나 사용자의 의견을 조작할 수 있습니다. [FaceForensics++]와 같은 딥페이크 감지 애플리케이션은 비디오를 분석하여 사용자를 가짜 비디오나 이미지로부터 보호합니다. 사용자가 웹에서 가짜 비디오를 시청하면 감지 애플리케이션이 사기성 비디오임을 실시간으로 경고합니다.
2.2. 프레임워크 사용 사례
이 섹션에서는 신경망 추론 하드웨어 가속을 위한 전용 저수준 API의 프레임워크 수준 사용 사례를 모아 설명합니다. 머신 러닝 프레임워크가 웹 신경망 API(WebNN API)의 주요 사용자가 되고, WebNN API를 통해 노출되는 저수준 세부 사항은 일반적인 웹 개발자에게 추상화될 것으로 예상됩니다. 그러나 머신 러닝에 특별한 관심과 역량이 있는 웹 개발자는 상위 수준 ML 프레임워크 대신 WebNN API와 직접 상호작용하기를 원할 수도 있습니다.
2.2.1. 사용자 정의 레이어
웹 애플리케이션 개발자가 WebNN API에서 DNN 모델을 실행하려고 합니다. 그러나 [LeakyReLU], [ELU] 등 일부 활성화 함수가 WebNN API에 포함되지 않았음을 확인했습니다. 이 문제를 해결하기 위해 개발자는 WebNN API 위에 추가 활성화 함수의 사용자 정의 레이어를 구성합니다. 사용자 정의 레이어의 범위에는 활성화뿐 아니라 컨볼루션, 정규화 등도 포함될 수 있습니다.
2.2.2. 네트워크 연결
웹 애플리케이션이 DNN 모델을 사용하며, 상위 컨볼루션 레이어와 하위 완전 연결 레이어의 모델 데이터는 별도의 파일에 저장됩니다. 이는 완전 연결 레이어의 모델 데이터가 서버 측 미세 조정으로 인해 주기적으로 업데이트되기 때문입니다.
따라서 애플리케이션은 처음에 두 부분 모델 파일을 모두 다운로드한 뒤 하나의 모델로 연결합니다. 모델이 업데이트되면 애플리케이션은 미세 조정된 모델 부분을 다운로드하고 완전 연결 레이어만 해당 부분으로 교체합니다.
2.2.3. 성능 적응
웹 애플리케이션 개발자가 모바일 장치에서 DNN 모델의 성능을 우려하고 있습니다. GPU 가속이 없는 모바일 장치에서는 모델이 너무 느리게 실행될 수 있음을 확인했습니다. 이 문제를 해결하기 위해 웹 애플리케이션은 WebNN API를 참조하여 가속을 사용할 수 있는지 확인하고, 가속이 없는 장치에 경고를 표시할 수 있도록 합니다.
몇 주 후 개발자는 CPU에서도 실행할 수 있는 작은 DNN 모델을 개발했습니다. CPU 실행을 지원하기 위해 애플리케이션을 수정하여 CPU 전용 장치에서는 작은 모델을 로드하도록 합니다.
2.2.4. 연산 수준 실행
JavaScript ML 프레임워크는 ML 모델을 로드하고 해석하고 실행하는 역할을 담당합니다. 모델 실행 단계에서 프레임워크는 모델의 연산을 순회하고 각 연산을 CPU, GPU 또는 ML 가속기와 같은 하드웨어 장치에서 실행합니다. 장치 간 불필요한 데이터 복사를 방지하기 위해 프레임워크는 연산 실행에 동일한 장치를 선택합니다. 컨볼루션 2D 또는 행렬 곱셈과 같이 계산 집약적인 연산의 경우 프레임워크는 WebNN API를 사용하여 선택한 장치에서 사용 가능한 ML 전용 가속을 통해 이를 실행합니다.
2.2.5. 실시간 비디오 처리와의 통합
실시간 비디오 처리를 사용하여 WebRTC 기반 화상 회의의 사용자 경험을 향상할 수 있습니다. 예를 들어 § 2.1.2 의미론적 분할 모델을 사용해 구현한 배경 흐림 기능은 사용자의 실시간 카메라 영상에서 배경을 흐리게 처리합니다. 이 사용 사례의 성능 요구 사항을 충족하기 위해 WebNN API는 미디어 파이프라인을 구성하는 다른 Web API의 기본 요소와 통합되어 WebNN API를 기반으로 실시간 비디오 스트림을 변환할 수 있도록 합니다.
3. 접근성 고려 사항
이 섹션에서는 신경망 추론 하드웨어 가속을 통해 구현되는 § 2.1 애플리케이션 사용 사례의 접근성을 개선하는 방법에 대해 웹 작성자에게 지침을 제공합니다. 이 지침은 이 명세에서 설명한 특정 사용 사례 이외에도 일반적으로 적용되며, 웹 작성자는 추가 접근성 지침을 위해 [wcag]를, 윤리적 원칙의 맥락에서 디지털 접근성을 위해 § 6 윤리적 고려 사항을 참조할 것을 권장합니다.
§ 2.1.8 이미지 캡셔닝은 캡션이 스크린 리더 및 기타 보조 기술(AT) 사용자에게 제공되도록 함으로써 개선할 수 있습니다. 웹 작성자는 생성된 이미지 캡션이 표준 alt 속성이나 기타 방법을 통해 해당 이미지와 의미론적으로 연결되도록 하는 것이 좋습니다. 사용할 방법은 설명이 최초 페이지 로드 시 업데이트되는지, 아니면 사용자 동작의 결과로 나중에 업데이트되는지에 따라 달라질 수 있습니다.
§ 2.1.11 감정 분석은 사용자에게 잘못된 레이블을 부여하고 그 결과 잘못 분류하여 차별적인 경험으로 이어질 수 있습니다. 웹 작성자는 신뢰도 점수를 공개하고 사용자가 이 기능을 끌 수 있는 옵션을 제공할 것을 권장합니다.
§ 2.1.13 노이즈 억제에서 강한 필터를 사용하면 구음장애가 있는 사용자의 음성이 제거되어 캡션과 인식이 실패할 수 있습니다. 웹 작성자는 우회 기능이나 감도 제어를 제공하고, 실시간 캡션이 활성화된 경우 노이즈 억제를 강제로 적용하지 않을 것을 권장합니다.
§ 2.2.5 실시간 비디오 처리와의 통합에서 배경 흐림 기반 분할은 방해 요소를 제거하는 데 도움이 되지만, 너무 많은 지연을 추가하여 입 모양 읽기와 실시간 캡션을 방해할 수 있습니다. 웹 작성자는 사용자에게 표시되는 키보드 및 스크린 리더로 조작 가능한 “배경 흐림 켜기/끄기” 제어를 다른 접근성/미디어 설정 옆에 제공할 것을 권장합니다.
§ 7.2 장치 선택을 통해 웹 작성자는 실행 속도와 전력 소비에 대한 선호도를 나타낼 수 있습니다. 구현자는 저사양 또는 배터리에 민감한 장치를 사용하는 사람이 특히 휴대용 AAC 또는 시선 추적 환경에서 캡션과 기타 중요한 접근성 기능의 반응성을 유지할 수 있도록 브라우저 UI에서 웹 작성자의 힌트를 사용자가 재정의할 수 있게 할 것을 권장합니다.
4. 보안 고려 사항
이 명세는 신경망 추론 하드웨어 가속을 위한 저수준 API를 정의합니다. 이 API는 사용자의 컴퓨터에 대한 저수준 접근 권한을 부여하므로 강력한 기능 [POWERFUL-FEATURES]으로 간주됩니다. 강력한 기능의 인증 및 기밀성 기대 사항을 충족하고 중간자 공격을 방지하기 위해 이 명세에서 정의한 모든 인터페이스는 보안 컨텍스트에서만 사용할 수 있습니다.이 API는 § 7.5 Permissions Policy 통합을 사용하여 모든 교차 출처 프레임에서 기본적으로 비활성화됩니다. 이를 통해 임베딩 페이지가 권한을 부여하는 정책을 명시적으로 설정하지 않는 한 서드파티 콘텐츠가 이 API를 사용하지 못하도록 합니다.
이 API를 사용하면 WebGPU 명세에서 정의한 GPUDevice로부터
MLContext를 생성할
수 있습니다.
이 컨텍스트의 보안 특성에 관한 자세한 내용은 WebGPU 보안 고려
사항을 참조하십시오.
이 API는 GPU, CPU 및 전용 ML 가속기 하드웨어 전반에 걸친 추상화를 제공합니다. GPU를 사용할 때는 WebGPU와 유사한 서비스 거부 고려 사항이 적용됩니다. CPU 또는 전용 ML 가속기를 사용할 경우 잠재적인 리소스 경합의 유형은 다르며, 완화 조치는 구현과 구성에 따라 달라집니다. 구현은 사이트가 과도한 양의 시스템 리소스를 사용하지 못하도록 플랫폼에서 사용할 수 있는 모든 메커니즘을 사용해야 합니다. 이러한 계산 장치는 공유 리소스이며, 어떤 계산 API를 사용하더라도 완전히 부하가 걸린 시스템의 전반적인 성능에 영향을 줍니다.
그래프가 완전히 구성되고 컴파일되면 그래프 내 각 연산의 입력 형상이 추론되고 확정됩니다. 실제 데이터에 대해 그래프를 실행하는 compute 메서드가 호출될 때 경계 검사가 수행됩니다. 이 단계 전에는 실제 데이터가 컴파일된 그래프에 바인딩되지 않습니다. 그 시점까지 이미 추론된 데이터 형상에 대해 적절한 경계 검사가 수행되도록 하는 것은 구현의 책임입니다.
구현자를 위한 지침으로 범위를 벗어난 접근에 취약한 연산을 문서화하십시오.
구현은 상수로 간주되는 데이터의 변경을 기반으로 한 제어 흐름 공격을 방어해야 합니다. 예를 들어 기반 플랫폼의 최적화는 계산 전체에서 가중치가 변경되지 않는다고 가정할 수 있습니다. API가 계산 도중 가중치를 보유한 버퍼의 내용을 변경할 수 있도록 허용한다면 이러한 최적화 가정이 무효화되어 기반 플랫폼에서 정의되지 않은 동작이 발생할 수 있습니다. API는 항상 버퍼를 복사하거나 전송함으로써 스크립트에서 발생하는 이러한 유형의 공격을 완화하지만, 구현은 상수로 간주되는 데이터의 프로세스 격리와 같은 추가 방어 수단도 고려해야 합니다.
미래 변화에 대비하기 위한 조치로 API 설계는 일반적으로 에뮬레이션할 수 있는 특정 연산을 호환성을 깨뜨리지 않고 보안, 성능 또는 기타 이유로 더 이상 사용하지 않도록 지정할 수 있게 합니다. 이는 이 명세에 정의된 더 작은 기본 연산으로 정의되는 상위 수준 함수 덕분에 가능합니다. 이를 통해 상위 수준 함수의 네이티브 구현을 polyfill 구현으로 대체할 수 있습니다.
CPU가 렌더러를 실행하는 프로세스 간에 공유되는 현재 상태를 고려하여 부채널 공격 가능성을 조사하십시오.
공격자가 결함이 있을 수 있는 특정 구현을 표적으로 삼지 못하게 하기 위해 § 7.2 장치 선택 메커니즘은 힌트일 뿐이며, 구체적인 장치 선택은 구현에 맡겨집니다. 예를 들어 사용자 에이전트는 알려진 취약점이 있는 장치에서는 모델을 실행하지 않도록 선택할 수 있습니다. 추가적인 완화책으로 장치 열거 메커니즘은 정의되지 않습니다.
힌트를 제공하면 우려 사항이 부분적으로 완화됩니다. 추가 완화책을 조사하십시오.
API 설계는 컴파일된 계산 그래프에 대한 공격 표면을 최소화합니다. 다양한 연산을 제공하는 MLGraphBuilder
인터페이스는 데이터 정의 API이므로 어떤 것도 실행하지 않고
데이터만 구성합니다. 따라서 공격 가능성은 MLContext.dispatch()
메서드를 호출하여 실행하기 전에 데이터를 그래프에 바인딩할 때로 제한됩니다. 이를 통해 구현자는 MLContext.dispatch()
메서드의 보안 강화에 집중할 수 있습니다. 예를 들어 데이터 경계를 준수하도록 하고 경계를
지키지 않았을 때 적절하게 실패하도록 할 수 있습니다.
고해상도 시간을 측정하도록 특별히 설계된 Web API는 해상도 감소, 지터 추가, 악용 탐지 및 API 호출 제한과 같은 기법을 사용하여 타이밍 공격을 완화합니다 [hr-time-3]. 실제 WebNN 구현 배포에서는 타이밍 공격을 비현실적으로 만들 정도의 충분한 지터가 발생할 가능성이 높지만 (예: IPC를 사용하기 때문에) 구현자는 타이밍 공격에 대해 구현을 고려하고 테스트할 것을 권고합니다.
참고: Unicode 시퀀스와 관련된 보안 위험은
label
USVString
정의의 맥락에서 설명합니다.
4.1. 새로운 연산에 대한 지침
이 섹션은 비규범적입니다.
이 명세에서 정의된 연산이 안전하게 구현될 수 있는 형태로 설계되도록 하기 위해, 이 섹션에서는 잠재적인 구현 문제를 줄이기 위해 연산을 어떻게 정의해야 하는지에 관한 지침을 제공합니다. 이러한 지침은 업계 모범 사례에 맞추어 시간이 지나면서 발전할 것으로 예상됩니다.
-
인수는 단순하게 구성하는 것을 우선하십시오
-
복잡한 데이터 형식에 파서를 사용하지 마십시오
-
연산을 저수준 기본 연산으로 분해할 수 있는 경우:
-
비규범적 에뮬레이션 경로를 추가하십시오
-
새로운 상위 수준 연산보다 기본 연산을 우선하되 성능상의 영향을 고려하십시오
-
-
연산 입력과 속성에 일관된 스타일을 따르십시오
-
풀링 및 축소와 같은 연산 계열에서는 API 형태와 옵션을 공유하십시오
-
가능하면 실패 사례를 테스트 사례로 형식화하십시오
-
확실하지 않다면 제외하십시오. 사용 사례를 충족할 수 있을 만큼 API 표면을 최대한 작게 유지하되, 그보다 더 작게 만들지는 마십시오
-
향후 발전을 방해할 수 있는 구현 세부 사항을 API에서 제외하도록 하며, 과도하게 명세하지 마십시오
-
빠르게 실패하십시오. 웹 개발자가 문제를 더 빨리 알수록 좋습니다
일반적으로 새로운 기능을 추가할 때는 Technical Architecture Group과 Privacy Interest Group의 [security-privacy-questionnaire]에 문서화된 보안 및 개인정보 보호 영향을 항상 고려하십시오.
5. 개인정보 보호 고려 사항
이 API는 민감한 사용자 데이터를 브라우저의 샌드박스 내에 유지하므로 클라우드 기반 추론 대안보다 개인정보 보호 측면에서 개선됩니다. 이미지, 오디오, 비디오 스트림 및 기타 개인정보와 같은 입력 데이터는 사용자의 장치를 벗어나지 않으므로 원격 서버로의 데이터 전송 및 서드파티 데이터 처리와 관련된 위험이 제거됩니다.
그러나 하드웨어 가속 기능과 밀접하게 상호작용하는 강력한 로컬 계산 API이므로 WebNN API는 성능 최적화와 개인정보 보호 사이에서 균형을 유지해야 합니다. 이 API에는 효과적인 머신 러닝 추론 기능을 제공하면서 핑거프린팅을 완화하기 위한 여러 개인정보 보호 조치가 포함되어 있습니다.
5.1. 핑거프린팅
설계상 이 API는 최상의 성능과 결과의 신뢰성을 갖추면서 식별된 § 2 사용 사례를 처리하는 데 필요한 최소한의 정보만 노출하는 것을 목표로 합니다. 우선 API는 표준화를 통해 핑거프린팅을 완화합니다. 즉, 다양한 플랫폼 API에서 일관된 동작을 정의하고 적합한 구현 전반에서 기반 하드웨어 차이에 관한 정보 누출을 최소화합니다. 이는 다음을 통해 이루어집니다.
-
하드웨어에 독립적이며 기반 플랫폼의 저수준 세부 정보 노출을 데이터 최소화 원칙에 따라 최소화하는 § 7.3 연산자.
-
웹 개발자가 실행 속도와 전력 소비에 대한 선호도를 표시할 수 있지만 실제 실행에 선택된 장치를 노출하지 않으며, 웹 개발자가 특정 장치를 열거하거나 선택하는 것도 허용하지 않는 § 8.2.1 MLContextOptions API. 이 힌트 메커니즘은 엔트로피를 추가하지 않습니다.
-
웹 개발자가 부채널을 사용해 정보를 추론하는 대신 명시적인 쿼리 API를 사용하여 특정 연산자의 지원 여부를 조회할 수 있게 하는 § 8.3.9 opSupportLimits() API. 이 API는 핑거프린팅 가능성에 기여할 수 있지만, 필요에 따라 버킷을 사용하여 이 API를 통해 노출되는 구별 가능한 구성의 수를 제한함으로써 엔트로피를 줄일 수 있습니다.
-
서로 다른 백엔드 구현 전반의 일관된 오류 처리.
전체 설계는 필요한 기능을 제공하면서 구현이 서로 다른 플랫폼에서 일관된 인터페이스를 유지하도록 합니다. 플랫폼별 세부 사항을 추상화함으로써 API는 기반 가속이 CPU, GPU 또는 전용 ML 하드웨어 중 무엇으로 제공되든 개인정보를 보호하는 예측 가능한 동작을 제공할 수 있습니다.
참고: MLContextOptions
는 활발히 개발 중이며, 추가 구현 경험과 더 넓은 웹 커뮤니티의 새로운 사용 사례를 바탕으로
설계가 변경될 것으로 예상됩니다.
그래프가 완전히 구성되고 컴파일된 후 실제 실행에 선택된 장치를 노출하기 위한
MLGraph.devices API 확장이 제안되었습니다. 이 API 확장의 개인정보 보호 영향은
조사 중입니다. [이슈 #836]
5.2. 실행 시간 분석
연산의 타이밍 특성은 기반 하드웨어 성능에 대한 일부 간접 정보를 제공할 수 있으며, 이는 모든 계산 API에 내재된 특성입니다. 특정 상황에서는 실행 시간 분석을 통해 한 기반 플랫폼의 신경망 하드웨어 가속 기능 성능을 다른 기반 플랫폼과 비교하여 간접적으로 알아낼 수 있습니다. 타이밍 공격에 관한 추가 설명은 § 4 보안 고려 사항도 참조하십시오.
참고: 그룹은 제안된 실행 시간 분석 핑거프린팅 벡터와 완화책에 관한 추가 의견을 환영합니다.
5.3. WebGPU 비교
WebGPU와 달리 이 API는 본질적으로 사용자 정의 셰이더 작성을 지원하지 않으므로
셰이더 캐시나 기타 영구 데이터를 이용하는 타이밍 공격에 취약하지 않습니다. 이 API는
브라우저 또는 기반 OS의 기존 셰이더와 저수준 기본 요소를 기반으로 합니다. GPUDevice와
상호작용하는 웹 개발자는 WebGPU
컴파일 캐시 고려 사항을 알고 있어야 합니다.
WebGPU API는 기기별 아티팩트를 개인정보 보호 고려 사항으로 식별합니다. 마찬가지로 WebNN API의 계산 장치 스케줄링도 특정 상황에서 핑거프린트를 만들 수 있습니다. 그러나 WebGPU와 마찬가지로 이러한 핑거프린트는 각 공급업체의 대부분 또는 모든 장치에서 동일하므로 우려가 완화됩니다. 또한 소프트웨어 구현을 사용하여 이러한 아티팩트를 더욱 제거할 수 있습니다.
일반적으로 이 API의 구현자는 적용 가능한 경우 WebGPU 개인정보 보호 고려 사항을 구현에 적용해야 합니다.
6. 윤리적 고려 사항
워킹 그룹은 규범적 명세에서 고려해야 할 완화책을 식별하는 데 도움을 주기 위해 웹에서 머신 러닝을 사용하는 것과 관련된 윤리적 문제를 문서화하기 시작했습니다. 워킹 그룹은 웹 머신 러닝을 위한 윤리 원칙 문서 [webmachinelearning-ethics]를 게시하고 유지하며, 전용 GitHub 저장소를 통해 더 넓은 커뮤니티의 기여를 받습니다.
7. 프로그래밍 모델
7.1. 개요
신경망의 핵심에는 수학 연산으로 이루어진 계산 그래프가 있습니다. 이러한 연산은 컴퓨터 비전, 자연어 처리 및 로보틱스 분야의 현대 머신 러닝 기술을 구성하는 기본 요소입니다. WebNN API는 신경망의 계산 그래프를 구성하고 컴파일하고 실행하기 위한 명세입니다.
MLGraph
인터페이스는 변경할 수 없는 컴파일된 계산 그래프(즉, 모델)를 나타냅니다.
MLGraphBuilder
인터페이스는 계산 그래프(그
그래프)를
구성하기 위한 빌더(팩터리) 역할을 하며, 이후 이를 컴파일하여 MLGraph를 생성합니다.
WebNN에서 계산 그래프는
데이터에 작용하며 그래프의 노드인 연산자로
구성됩니다. MLOperand는
계산 그래프 내에서 흐르는 데이터를 나타내며 그래프의 간선입니다. MLOperand에는
추론을 위한 계산 그래프의
입력 값, 추론에 사용되는 상수(학습된 가중치 포함),
추론 중 계산되는 중간 값(흔히 활성화라고 함), 그리고 추론의 출력
값이 포함됩니다. 연산자의 입력은 하나 이상의 MLOperand입니다.
연산자의 출력은 하나 이상의
MLOperand입니다.
연산자에는 동작을 제어하는 연산자별
매개변수가 있으며, 여기에는 0개 이상의 활성화 함수가 포함될 수
있습니다.
MLGraphBuilder
인터페이스의 핵심 부분은 gemm()
및 relu()와
같은 메서드입니다. 이 메서드는 계산이 실행될 때 입력 데이터에 수행할 실제 연산을 나타내는
연산자를 생성하고,
연산자를 보유한 새로운 MLOperand를
반환합니다. MLOperand를
생성하는 메서드는 모든 입력과 활성화를
연산자에 연결합니다. 각 메서드 호출은 다른 MLOperand의 값을
변경하지 않고
서로 다른 새로운 값을 반환합니다.
연산자에는 레이블이 있으며, 이는 예외 메시지와 같은 진단 정보에 포함될 수 있는 문자열입니다. 연산자가 생성되면 그 레이블은 구현
정의 방식으로 초기화되며 전달된 label을
포함할 수 있습니다.
dispatch()
중 오류를 보고하는
메커니즘을 추가하는 것을 고려하십시오.
[이슈 #778]
추론 시 모든 MLOperand는
본질적으로 다차원 배열인 텐서(실제 데이터)에 바인딩됩니다. 텐서의 표현은
구현에 따라 다르지만, 일반적으로 특정 버퍼(메모리)에 저장된 배열 데이터와
배열 데이터를 설명하는 일부 메타데이터(예: 형상)를 포함합니다.
계산 그래프 내의 연산에는 함수형 의미론이 있습니다. 이를 통해 구현은 여러 텐서 간에 배열 데이터를 공유할 수 있습니다. 예를 들어 reshape 또는 slice와 같은 연산의 구현은 입력 텐서와 동일한 버퍼를 공유하는 입력 텐서의 뷰를 반환할 수 있습니다. (reshape의 경우 전체 데이터가 공유되고, slice의 경우 입력 데이터의 일부가 공유됩니다.) 구현은 위와 같은 뷰를 중간 값에 사용할 수 있습니다.
실행 전에 하나 이상의 지정된 출력을 계산하는 데 사용되는 계산 그래프는 변환, 컴파일 및 최적화되어야 합니다. 컴파일 단계의 핵심 목적은 연산 또는 루프 융합과 같이 둘 이상의 연산에 걸친 최적화를 가능하게 하는 것입니다. 사용자 에이전트는 그래프 변환 중에도 이러한 최적화를 수행할 수 있습니다.
MLGraphBuilder.build()
메서드는 호출 스레드를 차단하지 않고 백그라운드에서 그래프를 컴파일하며, MLGraph로
이행되는 Promise를
반환합니다. 각 MLGraphBuilder는
최대 하나의 MLGraph만
빌드할 수 있습니다.
MLGraph의
기반 구현은 MLGraphBuilder의
연산자 및 MLOperand에 대응하는
연산자와 피연산자의 플랫폼별 표현으로 구성되지만,
이러한 표현은 스크립트에 표시되지 않으며 스크립트가 구성한 그래프를
결합하거나 분해한 형태일 수 있습니다.
MLGraph가
구성되면 MLContext.dispatch()
메서드는 CPU 실행의 경우 별도의 워커 스레드에 있는 병렬 타임라인에서, GPU 실행의 경우 GPU 명령 큐의
GPU 타임라인에서 그래프 실행을 비동기적으로 수행합니다. 이 메서드는 실제 실행이 다른 타임라인으로 오프로드되는 동안
호출 스레드를 차단하지 않고 즉시 반환합니다.
호출자는 MLNamedTensors를
사용하여 입력 값을 제공하고,
입력 MLOperand를
해당 값에 바인딩합니다. 호출자는 또한 출력 MLOperand를 위한
MLNamedTensors도
제공하며, 성공한 경우 여기에 그래프 실행 결과가 저장됩니다. 이 결과는 MLContext.readTensor(tensor)
메서드를 사용하여 스크립트로 다시 읽을 수 있습니다. 이러한 유형의 실행은 CPU, GPU 및 NPU 장치를 지원합니다.
7.2. 장치 선택
MLContext
인터페이스는 신경망 실행의 전역 상태를 나타냅니다. 중요한 컨텍스트 상태 중 하나는
리소스를 관리하고 신경망 그래프의 컴파일 및 최종 실행을 지원하는
기반 실행 장치입니다. MLContextOptions를
사용하는 기본 생성 방법 외에도 MLContext는
애플리케이션에서 이미 사용 중인 특정 GPUDevice로부터도
생성할 수 있습니다.
GPU 컨텍스트가 시스템 메모리에 있는 상수 또는 입력을 ArrayBufferView로
사용하여 그래프를 실행하는 상황에서는
입력 내용이 시스템 메모리에서 GPU 메모리로 자동 업로드되고, 그래프 실행이 끝나면
ArrayBufferView
출력 버퍼의 시스템 메모리로 다시 다운로드됩니다. 이러한 데이터 업로드 및 다운로드 주기는
GPU의 경우처럼 실행 장치에서 데이터를 시스템 메모리 밖으로 복사했다가 다시 복사해야 할 때만
발생합니다. 장치가 CPU인 경우에는 발생하지 않습니다. 또한
그래프 실행 결과는 알려진 레이아웃 형식으로 제공됩니다. 그래프 내 중간 결과에서는
네이티브 메모리 접근 패턴에 맞게 실행을 최적화할 수 있지만,
호출자의 관점에서 예상되는 동작을 유지하기 위해 그래프의 마지막 연산 출력은
그래프 끝에서 내용을 알려진 레이아웃 형식으로 다시 변환해야 합니다.
MLContext가
MLContextOptions로
생성되면 사용자 에이전트는 이러한 옵션을 고려하여 기반 실행 장치를 선택하고 생성합니다.
기반 플랫폼에 따라 사용자 에이전트는 서로 다른 CPU, NPU 및 GPU 장치 조합을 선택할 수 있습니다.
이 설계의 역사와 근거는 장치 선택 설명 문서를 참조하십시오.
7.3. 연산자
이 섹션은 비규범적입니다.
WebNN API는 주요 § 2.1 애플리케이션 사용 사례를 처리하는 잘 알려진 CNN 및 RNN, Transformer 및 생성형 모델에 필요한 연산자 집합을 정의합니다. 각 연산자의 세부 사항은 이 명세의 규범적 섹션에서 연산자 이름의 알파벳순으로 정의됩니다. API 표면의 기능적 개요를 제공하기 위해 이러한 연산자는 다음 비규범적 표에서 기능에 따라 범주로 그룹화됩니다.
참고: 일부 연산자는 여러 범주에 속합니다. 예를
들어 clamp()는
수학 함수이면서 활성화 함수로도 사용됩니다.
7.4. 태스크 소스
ML 태스크 소스는
MLGraph의 비동기 컴파일
및 실행과
MLContext의
생성과 관련된 모든
태스크에 사용되는
태스크 소스입니다.
전역 객체 global과 일련의 단계 steps가 주어졌을 때 ML 태스크를 큐에 넣으려면, 전역 태스크를 큐에 넣기를 ML 태스크 소스에서 global과 steps를 사용하여 수행합니다.
7.5. Permissions Policy 통합
이 명세는
"webnn"
문자열로 식별되는 정책 제어 기능을 정의합니다.
이 기능의 기본 허용 목록은 'self'입니다.
8. API
8.1. navigator.ml 인터페이스
ML 객체는 각각
Navigator
및 WorkerNavigator
인터페이스를 통해 Window
및 WorkerGlobalScope
컨텍스트에서 사용할 수 있으며 navigator.ml을 통해 노출됩니다.
interface mixin { [NavigatorML SecureContext ,SameObject ]readonly attribute ML ; };ml Navigator includes NavigatorML ;WorkerNavigator includes NavigatorML ;
8.2. ML
인터페이스
enum MLPowerPreference {"default" ,"high-performance" ,"low-power" };dictionary {MLContextOptions MLPowerPreference powerPreference = "default";boolean accelerated =true ; }; [SecureContext ,Exposed =(Window ,Worker )]interface {ML Promise <MLContext >createContext (optional MLContextOptions options = {});Promise <MLContext >createContext (GPUDevice gpuDevice ); };
8.2.1. MLContextOptions
참고: MLContextOptions
는 활발히 개발 중이며, 추가 구현 경험과 더 넓은 웹 커뮤니티의 새로운 사용 사례를 바탕으로
설계가 변경될 것으로 예상됩니다. 워킹 그룹은 대체 장치, 선호 순서에 따른 여러 장치 또는
특정 장치의 제외를 정의할 수 있도록 추가 API
제어를 검토하고 있습니다. 논의 중인 다른 고려 사항으로는 오류 처리, 최종
대체 수단 및 양자화 연산자가 있습니다. 이러한 설계 고려 사항에 대한 웹
개발자, 라이브러리 작성자, OS 및 하드웨어 공급업체와 기타 이해관계자의 의견은 GitHub를 통해 환영합니다. 핑거프린팅
고려 사항에 대한 추가 논의는 § 5 개인정보 보호 고려 사항을 참조하십시오.
powerPreference 옵션은 MLPowerPreference이며 전력 소비와 관련된 애플리케이션의
선호도를 나타냅니다. 다음 중 하나입니다.
- "
default" - 사용자 에이전트가 가장 적합한 동작을 선택하도록 합니다.
- "
high-performance" - 전력 소비보다 실행 속도를 우선합니다.
- "
low-power" - 실행 속도와 같은 다른 고려 사항보다 전력 소비를 우선합니다.
accelerated 옵션은 대규모 병렬 가속과 관련된 애플리케이션의
선호도를 나타냅니다. 이 옵션은 powerPreference보다
우선순위가 낮습니다.
true로 설정된 경우(기본값) 기반 플랫폼은 powerPreference에도
따라
GPU 또는 NPU와 같이 사용 가능한
대규모 병렬 가속기를 사용하려고 시도합니다.
false로 설정된 경우 애플리케이션은 CPU 추론을 선호한다는 것을 나타냅니다.
예를 들어 powerPreference
가 "high-performance"
이고 accelerated
가 false인 경우와 같이 서로 모순되는 입력이 있으면 구현은 기반
플랫폼에서 사용 가능한 최상의 일치 항목을 선택합니다(예를 들어 고성능 CPU 모드를 선택하거나, accelerated
가 powerPreference보다
우선순위가 낮으므로 이를 무시합니다).
8.2.2. createContext()
-
options:MLContextOptions. 컨텍스트에 대한 애플리케이션의 선호도를 제공합니다. -
gpuDevice:GPUDevice. 컨텍스트에서 사용할 특정 장치입니다.
MLContext.
realm realm과 options(GPUDevice
또는 MLContextOptions)가
주어졌을 때 컨텍스트를
생성하려면,
다음 단계를 실행합니다.
-
context를 realm의 새로운
MLContext로 둡니다. -
options가
GPUDevice객체이면 다음을 수행합니다.-
context.
[[contextType]]을 "webgpu"로 설정합니다. -
context.
[[powerPreference]]를"default"로 설정합니다. -
context.
[[accelerated]]를true로 설정합니다.
-
-
그렇지 않으면 다음을 수행합니다.
-
context.
[[contextType]]을 "default"로 설정합니다. -
options["
powerPreference"] 가 존재하면 context.[[powerPreference]]를 options["powerPreference"]로 설정합니다. -
그렇지 않으면 context.
[[powerPreference]]를"default"로 설정합니다. -
options["
accelerated"] 가 존재하면 context.[[accelerated]]를 options["accelerated"]로 설정합니다. -
그렇지 않으면 context.
[[accelerated]]를true로 설정합니다.
-
-
사용자 에이전트가 context.
[[contextType]]을 지원할 수 없으면 실패를 반환합니다. -
context를 반환합니다.
createContext(options)의 단계는 다음과 같습니다.
-
global의 연관된 Document가 사용이 허용되지 않은 webnn 기능이면 realm에서 "
SecurityError"DOMException으로 거부된 새 promise를 반환합니다. -
promise를 realm의 새 promise로 둡니다.
-
다음 단계를 병렬로 실행합니다.
-
context를 realm과 options이 주어진 상태에서 컨텍스트를 생성한 결과로 둡니다. 실패가 반환되면 global을 사용하여 ML 태스크를 큐에 넣어 promise를 "
NotSupportedError"DOMException으로 거부하고 이 단계를 중단합니다. -
global을 사용하여 ML 태스크를 큐에 넣어 promise를 context로 이행합니다.
-
-
promise를 반환합니다.
createContext(gpuDevice) 메서드의
단계는 다음과 같습니다.
-
global의 연관된 Document가 사용이 허용되지 않은 webnn 기능이면 realm에서 "
SecurityError"DOMException으로 거부된 새 promise를 반환합니다. -
promise를 realm의 새 promise로 둡니다.
-
다음 단계를 병렬로 실행합니다.
-
context를 realm과 gpuDevice가 주어진 상태에서 컨텍스트를 생성한 결과로 둡니다. 실패가 반환되면 global을 사용하여 ML 태스크를 큐에 넣어 promise를 "
NotSupportedError"DOMException으로 거부하고 이 단계를 중단합니다. -
global을 사용하여 ML 태스크를 큐에 넣어 promise를 context로 이행합니다.
-
-
promise를 반환합니다.
8.3. MLContext
인터페이스
MLContext
인터페이스는 신경망 계산 워크로드 및 실행 프로세스의 전역 상태를 나타냅니다. 각 MLContext 객체에는
연관된 컨텍스트 유형과 MLPowerPreference가
있습니다.
typedef record <USVString ,MLTensor >;MLNamedTensors dictionary {MLContextLostInfo DOMString message ; }; [SecureContext ,Exposed =(Window ,Worker )]interface {MLContext undefined dispatch (MLGraph graph ,MLNamedTensors inputs ,MLNamedTensors outputs );Promise <MLTensor >createTensor (MLTensorDescriptor descriptor );Promise <MLTensor >createExportableTensor (MLTensorDescriptor descriptor ,GPUDevice gpuDevice );Promise <MLTensor >createConstantTensor (MLOperandDescriptor descriptor ,AllowSharedBufferSource inputData );Promise <ArrayBuffer >readTensor (MLTensor tensor );Promise <undefined >readTensor (MLTensor tensor ,AllowSharedBufferSource outputData );undefined writeTensor (MLTensor tensor ,AllowSharedBufferSource inputData );GPUBuffer exportToGPU (MLTensor tensor );MLOpSupportLimits ();opSupportLimits undefined destroy ();readonly attribute boolean accelerated ;readonly attribute Promise <MLContextLostInfo >lost ; };
MLContext
에는 다음 내부 슬롯이 있습니다.
[[contextType]]의 유형은 컨텍스트 유형입니다.[[powerPreference]]의 유형은MLPowerPreference입니다.[[accelerated]]의 유형은boolean입니다.-
MLContext의 처리 유형(CPU 또는 대규모 병렬 처리)입니다. [[lost]]의 유형은Promise<MLContextLostInfo>입니다.[[timeline]]-
MLContext의 계산 장치에서 연산을 실행하는 것과 연관된 타임라인입니다. 이러한 연산에는 계산 그래프에 대한 추론 및MLTensor의[[data]]수정이 포함됩니다.이 타임라인을 더 엄밀하게 정의하십시오. [이슈 #529]
컨텍스트 유형은 리소스를 관리하고 신경망 그래프의 컴파일 및 실행을 지원하는 실행 컨텍스트의 유형입니다.
- "default"
- 사용자 선호 옵션에 따라 생성된 컨텍스트입니다.
- "webgpu"
- WebGPU 장치에서 생성된 컨텍스트입니다.
AllowSharedBufferSource
bufferSource와 MLOperandDescriptor
descriptor가 주어졌을 때 descriptor를 사용하여 buffer를 검증하려면 다음 단계를 실행합니다.
-
bufferSource의 바이트 길이가 descriptor의 바이트 길이와 같지 않으면 false를 반환합니다.
-
bufferSource의 유형에 따라 분기합니다.
ArrayBuffer-
true를 반환합니다.
SharedArrayBuffer-
true를 반환합니다.
ArrayBufferView-
-
bufferSource가
Uint8Array객체이면 true를 반환합니다. -
bufferSource가 이 표에 따라 descriptor의
dataType과 일치하면 true를 반환합니다. -
false를 반환합니다.
-
참고: descriptor의 dataType과
관계없이 Uint8Array를
사용하는 것은 예를 들어 WebAssembly.Memory
인스턴스의 일부와 같이 ArrayBuffer의
슬라이스를 표현하는 일반적인 방법으로 지원됩니다. 개발자는 가독성과 유지보수성을 위해 WebNN 코드를 작성할 때
보다 구체적인 뷰 유형을 사용할 것을 권장합니다.
record<USVString,
MLOperandDescriptor>
namedDescriptors를 사용하여 MLNamedTensors
namedTensors가 주어졌을 때 descriptor를 사용하여 tensor를 검증하려면:
-
namedTensors의 크기가 namedDescriptors의 크기와 같지 않으면 false를 반환합니다.
-
namedTensors의 각 name → tensor에 대해 각각:
-
tensor.
[[isConstant]]가 true이면 false를 반환합니다. -
namedDescriptors[name]이 존재하지 않으면 false를 반환합니다.
-
tensor.
[[descriptor]]가 namedDescriptors[name]과 같지 않으면 false를 반환합니다.
-
-
true를 반환합니다.
8.3.1.
dispatch()
컴파일된 MLGraph의 계산
워크로드를
MLContext의
[[timeline]]에
스케줄합니다.
-
graph:MLGraph. 실행할 계산 그래프입니다. -
inputs:MLNamedTensors. 계산 그래프의 입력입니다. -
outputs:MLNamedTensors. 계산 그래프의 출력입니다.
반환: undefined.
참고: dispatch() 자체는 그래프 실행이
완료되었다는 신호를 제공하지 않습니다. 대신 호출자는 출력 tensor를 다시 읽은 결과를 await할 수 있습니다.
아래의 § 8.3.1.1 예제를 참조하십시오.
dispatch(graph, inputs, outputs)
메서드의 단계는 다음과 같습니다.
-
graph.
[[context]]가 this가 아니면TypeError를 throw합니다. -
graph.
[[isDestroyed]]가 true이면 "InvalidStateError"DOMException을 throw합니다. -
allTensors를 inputs의 값에 outputs의 값을 확장하여 구성한
MLTensor의 목록으로 둡니다. -
allTensors의 각 tensor에 대해 각각:
-
tensor.
[[context]]가 this가 아니면TypeError를 throw합니다. -
tensor.
[[isDestroyed]]가 true이면TypeError를 throw합니다.
-
-
inputs와 graph.
[[inputDescriptors]]가 주어진 상태에서 descriptor를 사용하여 tensor를 검증한 결과가 false이면TypeError를 throw합니다. -
outputs와 graph.
[[outputDescriptors]]가 주어진 상태에서 descriptor를 사용하여 tensor를 검증한 결과가 false이면TypeError를 throw합니다. -
다음 단계를 graph.
[[context]].[[timeline]]에 큐잉합니다.-
다음 단계를 실행하되, this가 손실될 때 중단합니다.
-
inputs와 outputs을 사용하여 graph.
[[implementation]]에 계산 요청을 발행합니다.그래프 실행 중 오류를 보고하는 메커니즘을 추가하십시오. [이슈 #778]
-
-
tensor를 사용하여 상수 피연산자를 생성한 경우 build가 완료된 후 해당 tensor를 파기하는 것은 허용됩니다. 구현은 이러한 파기로 인해 컴파일된 그래프가 영향을 받지 않고 유효한 상태를 유지하도록 해야 합니다.
8.3.1.1. 예제
다음 코드는 MLTensor를
사용하여 MLGraph를
실행하는 방법을 보여줍니다.
const descriptor= { dataType: 'float32' , shape: [ 2 , 2 ] }; const context= await navigator. ml. createContext(); const builder= new MLGraphBuilder( context); // 1. 계산 그래프 'C = 0.2 * A + B'를 생성합니다. const constant= builder. constant( descriptor, new Float32Array( 4 ). fill( 0.2 )); const A= builder. input( 'A' , descriptor); const B= builder. input( 'B' , descriptor); const C= builder. add( builder. mul( A, constant), B); // 2. 그래프를 컴파일합니다. const graph= await builder. build({ 'C' : C}); // 3. 재사용 가능한 입력 및 출력 tensor를 생성합니다. const [ inputTensorA, inputTensorB, outputTensorC] = await Promise. all([ context. createTensor({ dataType: A. dataType, shape: A. shape, writable: true }), context. createTensor({ dataType: B. dataType, shape: B. shape, writable: true }), context. createTensor({ dataType: C. dataType, shape: C. shape, readable: true }) ]); // 4. 입력을 초기화합니다. context. writeTensor( inputTensorA, new Float32Array( 4 ). fill( 1.0 )); context. writeTensor( inputTensorB, new Float32Array( 4 ). fill( 0.8 )); // 5. 그래프를 실행합니다. const inputs= { 'A' : inputTensorA, 'B' : inputTensorB}; const outputs= { 'C' : outputTensorC}; context. dispatch( graph, inputs, outputs); // 6. 계산된 결과를 다시 읽습니다. const result= await context. readTensor( outputTensorC); console. log( '출력 값:' , new Float32Array( result)); // [1, 1, 1, 1]
8.3.2.
createTensor()
이 MLContext와
연관된 MLTensor를
생성합니다.
-
descriptor:MLTensorDescriptor.
createTensor(descriptor) 메서드의 단계는
다음과 같습니다.
-
this가 손실된 상태이면 realm에서 "
InvalidStateError"DOMException으로 거부된 새 promise를 반환합니다. -
tensor를 this와 descriptor가 주어진 상태에서 MLTensor를 생성한 결과로 둡니다.
-
promise를 realm의 새 promise로 둡니다.
-
다음 단계를 this.
[[timeline]]에 큐잉합니다.-
다음 단계를 실행하되, this가 손실될 때 중단합니다.
-
descriptor를 사용하여 tensor.
[[data]]를 생성하고 모든 바이트를 0으로 초기화합니다. -
실패하면 global을 사용하여 ML 태스크를 큐에 넣어 promise를 "
UnknownError"DOMException으로 거부하고 이 단계를 중단합니다. -
그렇지 않으면 global을 사용하여 ML 태스크를 큐에 넣어 promise를 tensor로 이행합니다.
-
-
중단된 경우, global을 사용하여 ML 태스크를 큐에 넣어 promise를 "
InvalidStateError"DOMException으로 거부합니다.
-
-
promise를 반환합니다.
8.3.3. createExportableTensor()
이 MLContext와
연관되고
exportToGPU()를
사용하여 주어진 GPUDevice로
내보낼 수 있는 MLTensor를 생성합니다.
-
descriptor:MLTensorDescriptor. -
gpuDevice:GPUDevice. tensor를 내보낼 수 있는 장치입니다.
createExportableTensor(descriptor, gpuDevice)
메서드의 단계는 다음과 같습니다.
-
this가 손실된 상태이면 realm에서 "
InvalidStateError"DOMException으로 거부된 새 promise를 반환합니다. -
gpuDevice가 손실된 상태이면 realm에서 새 promise를 반환하며, 이 promise는 "
InvalidStateError"DOMException으로 거부됩니다. -
this가
MLTensor를 gpuDevice로 내보내는 것을 지원할 수 없으면 realm에서 새 promise를 반환하며, 이 promise는 "NotSupportedError"DOMException으로 거부됩니다.참고:
MLContext가 주어진GPUDevice로의 내보내기를 지원하는지 여부는 구현 정의이며,MLContext의 컨텍스트 유형과 기반 플랫폼에 따라 달라질 수 있습니다. -
tensor를 this, descriptor 및 gpuDevice가 주어진 상태에서 내보낼 수 있는 MLTensor를 생성한 결과로 둡니다.
-
promise를 realm의 새 promise로 둡니다.
-
다음 단계를 this.
[[timeline]]에 큐잉합니다.-
다음 단계를 실행하되, this가 손실될 때 중단합니다.
-
descriptor를 사용하여 tensor.
[[data]]를 생성하고 모든 바이트를 0으로 초기화합니다. -
실패하면 global을 사용하여 ML 태스크를 큐에 넣어 promise를 "
UnknownError"DOMException으로 거부하고 이 단계를 중단합니다. -
그렇지 않으면 global을 사용하여 ML 태스크를 큐에 넣어 promise를 tensor로 이행합니다.
-
-
중단된 경우, global을 사용하여 ML 태스크를 큐에 넣어 promise를 "
InvalidStateError"DOMException으로 거부합니다.
-
-
promise를 반환합니다.
8.3.4. createConstantTensor()
이 MLContext와
연관된 상수 MLTensor를 생성합니다.
-
descriptor:MLOperandDescriptor입니다. -
inputData:AllowSharedBufferSource입니다. 바이트가 tensor에 기록될 buffer입니다.
createConstantTensor(descriptor, inputData)
메서드의 단계는 다음과 같습니다.
-
this가 손실된 상태이면 realm에서 "
InvalidStateError"DOMException으로 거부된 새 promise를 반환합니다. -
descriptor가 주어진 상태에서 차원을 검사한 결과가 false이면 realm에서
TypeError로 거부된 새 promise를 반환합니다. -
inputData와 descriptor가 주어진 상태에서 descriptor를 사용하여 buffer를 검증한 결과가 false이면 realm에서
TypeError로 거부된 새 promise를 반환합니다. -
bytes를 inputData가 주어진 상태에서 buffer source가 보유한 바이트의 복사본을 가져온 결과로 둡니다.
-
tensor를 this와 descriptor가 주어진 상태에서 상수 MLTensor를 생성한 결과로 둡니다.
-
promise를 realm의 새 promise로 둡니다.
-
다음 단계를 this.
[[timeline]]에 큐잉합니다.-
다음 단계를 실행하되, this가 손실될 때 중단합니다.
-
descriptor가 주어진 상태에서 tensor.
[[data]]를 생성합니다. -
실패하면 global을 사용하여 ML 태스크를 큐에 넣어 promise를 "
UnknownError"DOMException으로 거부하고 이 단계를 중단합니다. -
bytes를 tensor.
[[data]]에 복사합니다. -
실패하면 global을 사용하여 ML 태스크를 큐에 넣어 promise를 "
UnknownError"DOMException으로 거부하고 이 단계를 중단합니다. -
그렇지 않으면 global을 사용하여 ML 태스크를 큐에 넣어 promise를 tensor로 이행합니다.
-
-
중단된 경우, global을 사용하여 ML 태스크를 큐에 넣어 promise를 "
InvalidStateError"DOMException으로 거부합니다.
-
-
promise를 반환합니다.
8.3.5.
readTensor(tensor)
MLContext.[[timeline]]에서
MLTensor의
[[data]]를
스크립트로 다시 읽습니다.
-
tensor:MLTensor입니다. 읽을 tensor입니다.
반환: Promise<ArrayBuffer>입니다.
읽기 결과를 포함하는 buffer입니다.
readTensor(tensor) 메서드의 단계는 다음과 같습니다.
-
tensor.
[[context]]가 this가 아니면 realm에서TypeError로 거부된 새 promise를 반환합니다. -
tensor.
[[isDestroyed]]가 true이면 realm에서TypeError로 거부된 새 promise를 반환합니다. -
tensor.
[[descriptor]].readable이 false이면 realm에서TypeError로 거부된 새 promise를 반환합니다. -
promise를 realm의 새 promise로 둡니다.
-
promise를 tensor.
[[pendingPromises]]에 추가합니다. -
다음 단계를 tensor.
[[context]].[[timeline]]에 큐잉합니다.-
다음 단계를 실행하되, this가 손실될 때 중단합니다.
-
실패하면 global을 사용하여 ML 태스크를 큐에 넣고 다음 단계를 수행합니다.
-
promise를 tensor.
[[pendingPromises]]에서 제거합니다. -
promise를 "
UnknownError"DOMException으로 거부하고 이 단계를 중단합니다.
-
-
그렇지 않으면 global을 사용하여 ML 태스크를 큐에 넣고 다음 단계를 수행합니다.
-
promise를 tensor.
[[pendingPromises]]에서 제거합니다. -
buffer를 realm에서 bytes로부터
ArrayBuffer를 생성한 결과로 둡니다. -
promise를 buffer로 이행합니다.
-
-
중단된 경우, global을 사용하여 ML 태스크를 큐에 넣어 promise를 "
InvalidStateError"DOMException으로 거부합니다.
-
-
promise를 반환합니다.
8.3.6.
readTensor(tensor, outputData)
readTensor(tensor)의
자체 buffer 제공 변형입니다.
MLTensor의
[[data]]를
제공된 buffer로 다시 읽습니다.
-
tensor:MLTensor입니다. 읽을 tensor입니다. -
outputData:AllowSharedBufferSource입니다. 결과를 읽어 넣을 buffer입니다.
readTensor(tensor, outputData)
메서드의 단계는 다음과 같습니다.
-
tensor.
[[context]]가 this가 아니면 realm에서TypeError로 거부된 새 promise를 반환합니다. -
tensor.
[[isDestroyed]]가 true이면 realm에서TypeError로 거부된 새 promise를 반환합니다. -
tensor.
[[descriptor]].readable이 false이면 realm에서TypeError로 거부된 새 promise를 반환합니다. -
outputData와 tensor.
[[descriptor]]가 주어진 상태에서 descriptor를 사용하여 buffer를 검증한 결과가 false이면 realm에서TypeError로 거부된 새 promise를 반환합니다. -
promise를 realm의 새 promise로 둡니다.
-
promise를 tensor.
[[pendingPromises]]에 추가합니다. -
다음 단계를 tensor.
[[context]].[[timeline]]에 큐잉합니다.-
다음 단계를 실행하되, this가 손실될 때 중단합니다.
-
실패하면 global을 사용하여 ML 태스크를 큐에 넣어 다음 단계를 실행합니다.
-
promise를 tensor.
[[pendingPromises]]에서 제거합니다. -
promise를 "
UnknownError"DOMException으로 거부하고 이 단계를 중단합니다.
-
-
그렇지 않으면 global을 사용하여 ML 태스크를 큐에 넣어 다음 단계를 실행합니다.
-
promise를 tensor.
[[pendingPromises]]에서 제거합니다. -
outputData가 분리된 상태이면 promise를
TypeError로 거부하고 이 단계를 중단합니다.참고: 위의 descriptor를 사용한 buffer 검증은 outputData가 분리된 상태이면 실패하지만, 해당 단계와 이 단계 사이에 outputData가 분리될 수도 있습니다.
-
bytes를 outputData에 기록합니다.
-
-
중단된 경우, global을 사용하여 ML 태스크를 큐에 넣어 promise를 "
InvalidStateError"DOMException으로 거부합니다.
-
-
promise를 반환합니다.
8.3.7.
writeTensor()
MLContext의
[[timeline]]에서
MLTensor의
[[data]]에
데이터를 기록합니다.
-
tensor:MLTensor입니다. 데이터를 기록할 tensor입니다. -
inputData:AllowSharedBufferSource입니다. 바이트가 tensor에 기록될 buffer입니다.
반환: undefined입니다.
writeTensor(tensor, inputData)
메서드의 단계는 다음과 같습니다.
-
tensor.
[[context]]가 this가 아니면TypeError를 throw합니다. -
tensor.
[[isDestroyed]]가 true이면TypeError를 throw합니다. -
tensor.
[[descriptor]].writable이 false이면TypeError를 throw합니다. -
inputData와 tensor.
[[descriptor]]가 주어진 상태에서 descriptor를 사용하여 buffer를 검증한 결과가 false이면TypeError를 throw합니다. -
bytes를 inputData가 주어진 상태에서 buffer source가 보유한 바이트의 복사본을 가져온 결과로 둡니다.
-
단언: bytes의 길이는 tensor.
[[descriptor]]의 바이트 길이와 같습니다. -
다음 단계를 tensor.
[[context]].[[timeline]]에 큐잉합니다.
참고: dispatch()와 마찬가지로
writeTensor() 자체는 기록이 완료되었다는 신호를 제공하지 않습니다. tensor의 내용을 검사하려면
호출자는 tensor를 다시 읽은 결과를 await할 수 있습니다.
8.3.8.
exportToGPU()
내보낼 수 있는 MLTensor를 연관된
GPUDevice에
GPUBuffer로
내보내고,
반환된 GPUBuffer가
파기될 때까지 해당 GPUDevice에
이를 대여합니다.
MLTensor가 내보내진 상태인 동안
[[gpuDevice]]는
MLTensor의
내용에 독점적으로 접근하며, MLTensor에 의존하는
모든 WebNN 연산 —
dispatch(),
readTensor(tensor),
readTensor(tensor, outputData),
및 writeTensor()
— 은 TypeError를
throw합니다.
반환된 GPUBuffer는
GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST의 usage와
MLTensor의
[[descriptor]]의
바이트 길이와 같은 size로
생성됩니다.
반환된 GPUBuffer가
파기되면
MLTensor는
MLContext로
반환되며
WebNN 연산에서 다시 사용할 수 있습니다.
참고: MLTensor 내보내기가
zero-copy라는 보장은 없습니다. MLTensor을 뒷받침하는
메모리에
[[gpuDevice]]가
접근할 수 없다면
내보내기에는 MLTensor의
내용을 반환되는 GPUBuffer로
복사하고,
GPUBuffer가
파기되면 다시 복사해야 할 수 있습니다.
exportToGPU(tensor) 메서드의 단계는 다음과 같습니다.
-
tensor.
[[context]]가 this가 아니면TypeError를 throw합니다. -
tensor.
[[isDestroyed]]가 true이면TypeError를 throw합니다. -
tensor.
[[exportableToGPU]]가 false이면TypeError를 throw합니다. -
gpuDevice를 tensor.
[[gpuDevice]]로 둡니다. -
gpuDevice가 손실된 상태이면 "
InvalidStateError"DOMException을 throw합니다. -
tensor가 내보내진 상태이면 tensor.
[[exportedBuffer]]를 반환합니다. -
usage를
GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST로 둡니다. -
buffer를 realm에서 gpuDevice와 연관된 새로운
GPUBuffer로 두며, 그size는 tensor.[[descriptor]]의 바이트 길이이고, 그usage는 usage입니다. -
다음 단계를 tensor.
[[context]].[[timeline]]에 큐잉합니다. -
tensor.
[[exportedBuffer]]를 buffer로 설정합니다. -
buffer를 반환합니다.
사용자 에이전트는 위에서 큐잉된, buffer의 내용이 tensor.[[data]]를
반영하도록 하는 단계가 완료되기 전에 buffer에서 읽거나 buffer에 쓰는
gpuDevice의 GPUQueue에
큐잉된 연산이 실행되지 않도록 반드시 보장해야 합니다.
참고: 이 순서 보장은 사용자
에이전트 내부의 것이며, 애플리케이션 측에서 관찰 가능한 동기화를 수행할 필요가 없습니다. 애플리케이션은
exportToGPU()가
반환된 직후 buffer를 사용하는 GPUQueue
작업을 안전하게 기록하고 제출할 수 있습니다.
exportToGPU()가
반환한 GPUBuffer가
파기되면 사용자 에이전트는 내보낸 원본 MLTensor가 주어진
상태에서 반드시 내보낸 MLTensor를 반환해야 합니다.
참고: MLTensor 또는 해당
MLContext를
내보낸
상태인 동안 파괴해도 반환된 GPUBuffer는
무효화되지 않습니다;
GPUBuffer는
파괴될 때까지 [[gpuDevice]]에서
계속 사용할 수 있습니다.
참고: MLTensor가 내보내진 상태인 동안
[[gpuDevice]]가
손실된 상태가 되더라도 반환된 GPUBuffer는
암묵적으로 파기되지 않으며, MLTensor는
애플리케이션이 destroy()를
호출할 때까지
내보내진 상태로 유지됩니다
(따라서 WebNN 연산에서는 사용할 수 없습니다). destroy()는 gpuDevice가 손실된 후에도
계속 유효하게 호출할 수 있습니다.
8.3.8.1. 예제
다음 코드는 내보낼 수 있는 tensor를 사용하는 최소한의 WebNN에서 WebGPU로의 흐름을 보여줍니다.
// 1. WebGPU 및 WebNN 컨텍스트를 생성합니다. const gpuAdapter= await navigator. gpu. requestAdapter(); const gpuDevice= await gpuAdapter. requestDevice(); const context= await navigator. ml. createContext(); // 2. 간단한 그래프를 빌드합니다: y = x + 1. const builder= new MLGraphBuilder( context); const descriptor= { dataType: 'float32' , shape: [ 4 ]}; const x= builder. input( 'x' , descriptor); const one= builder. constant( descriptor, new Float32Array([ 1 , 1 , 1 , 1 ])); const y= builder. add( x, one); const graph= await builder. build({ y}); // 3. 내보낼 수 있는 tensor를 생성하고 WebNN dispatch를 실행합니다. const inputTensor= await context. createExportableTensor( { dataType: 'float32' , shape: [ 4 ], writable: true }, gpuDevice); const outputTensor= await context. createExportableTensor( { dataType: 'float32' , shape: [ 4 ], readable: true }, gpuDevice); context. writeTensor( inputTensor, new Float32Array([ 1 , 2 , 3 , 4 ])); context. dispatch( graph, { x: inputTensor}, { y: outputTensor}); // 4. WebGPU로 내보내고 GPU 명령에서 사용합니다. const gpuBuffer= context. exportToGPU( outputTensor); // ... WebGPU 계산/렌더링 작업에서 gpuBuffer를 사용합니다 ... // 5. tensor를 WebNN으로 반환한 다음 WebNN에서 다시 읽습니다. gpuBuffer. destroy(); const result= new Float32Array( await context. readTensor( outputTensor)); console. log( result); // [2, 3, 4, 5]
8.3.9.
opSupportLimits()
opSupportLimits()는
구현마다 연산자 수준에서 달라지는 지원 수준을 노출합니다. WebNN API 사용자는 각 대상 플랫폼에 배포할
최적의 모델 아키텍처를 결정하기 위해 opSupportLimits()를
사용하여 기능 지원 수준을 확인하는 것이 좋습니다.
참고: opSupportLimits()
API는 브라우저 핑거프린팅을 위한 추가 엔트로피를 제공하기 위한 것이 아닙니다. 현재 구현에서는
이 기능 지원 정보를 OS와 브라우저 버전만으로 추론할 수 있습니다. 향후 구현의 다양성이
이를 필요로 한다면, 이 API는 향후 구현에서 엔트로피를 줄이기 위해 예를 들어 WebGPU와 유사하게 기능을
버킷화하는 새로운 개인정보 보호 완화책을 추가할 수 있도록 합니다.
핑거프린팅 고려 사항에 대한 추가 논의는 § 5 개인정보 보호 고려 사항을 참조하십시오.
8.3.9.1. MLOpSupportLimits
dictionary
MLOpSupportLimits에는
다음과 같은 최상위 멤버가 있으며, 이들 외에도 각 연산자에는 해당 빌더
메서드에 정의된 대응 멤버가 있습니다.
dictionary {MLOpSupportLimits MLInputOperandLayout preferredInputLayout ; [EnforceRange ]unsigned long long maxTensorByteLength ;MLTensorLimits input ;MLTensorLimits constant ;MLTensorLimits output ; };
preferredInputLayout, 유형은 MLInputOperandLayout-
conv2d()와 같이 레이아웃에 의존하는 연산자의 선호 입력 레이아웃입니다. maxTensorByteLength, 유형은 unsigned long long-
지원되는 tensor의 최대 길이(바이트 단위)입니다.
input, 유형은 MLTensorLimitsconstant, 유형은 MLTensorLimitsoutput, 유형은 MLTensorLimits
8.3.9.2. MLRankRange
dictionary
dictionary {MLRankRange unsigned long min ;unsigned long max ; };
min, 유형은 unsigned long-
지원되는 최소 rank입니다.
max, 유형은 unsigned long-
지원되는 최대 rank입니다.
8.3.9.3. MLTensorLimits
dictionary
typedef sequence <MLOperandDataType >;MLDataTypeList dictionary {MLTensorLimits MLDataTypeList dataTypes ;MLRankRange rankRange ; };
dataTypes, 유형은 MLDataTypeList-
지원되는 데이터 유형입니다.
rankRange, 유형은 MLRankRange-
지원되는 최소 및 최대 rank입니다.
8.3.9.4. MLBinarySupportLimits
dictionary
dictionary {MLBinarySupportLimits MLTensorLimits a ;MLTensorLimits b ;MLTensorLimits output ; };
a, 유형은 MLTensorLimits-
a operand에 대한
MLTensorLimits입니다. b, 유형은 MLTensorLimits-
b operand에 대한
MLTensorLimits입니다. output, 유형은 MLTensorLimits-
출력 operand에 대한
MLTensorLimits입니다.
8.3.9.5. MLSingleInputSupportLimits
dictionary
dictionary {MLSingleInputSupportLimits MLTensorLimits input ;MLTensorLimits output ; };
input, 유형은 MLTensorLimits-
입력 operand에 대한
MLTensorLimits입니다. output, 유형은 MLTensorLimits-
출력 operand에 대한
MLTensorLimits입니다.
8.3.10.
destroy()
destroy()
메서드를 호출하여 컨텍스트와 관련된 모든 리소스를 해제할 수 있습니다. 미처리된 모든 계산 요청과
MLTensor
생성/읽기/쓰기 요청은 실패합니다.
destroy() 메서드의 단계는 다음과 같습니다.
8.3.11. 오류
사용자 에이전트가 MLContext를
더 이상 요청 처리에 사용할 수 없다고 판단하면 해당 컨텍스트에 대해 컨텍스트 손실 단계를 실행해야 합니다.
MLContext
context에 대한 컨텍스트
손실
단계는 다음과 같습니다.
-
global을 context의 관련 전역 객체로 둡니다.
-
global을 사용하여 ML 태스크를 큐에 넣고 다음 단계를 실행합니다.
DOMString
message를 사용하여 MLContext
context를 손실시키려면:
-
info를 새로운
MLContextLostInfo로 둡니다. -
info.
message를 message로 설정합니다. -
graph.
[[context]]가 this와 같은 각MLGraphgraph에 대해: -
tensor.
[[context]]가 this와 같은 각MLTensortensor에 대해:
message, 유형은 DOMString-
발생한 오류에 대한 정보를 제공하는 구현 정의 메시지입니다.
MLContext
손실된 상태인 것은 해당 [[lost]]
Promise가
settled 상태인 경우입니다.
8.4. MLGraph
인터페이스
MLGraph
인터페이스는 컴파일된 계산 그래프를 나타냅니다. 컴파일된 그래프는 한 번 구성되면 변경할 수 없으며 이후에
수정할 수 없습니다.
[SecureContext ,Exposed =(Window ,Worker )]interface {MLGraph undefined destroy (); };
MLGraph에는
다음 내부 슬롯이 있습니다.
[[context]]의 유형은MLContext입니다.[[inputDescriptors]]의 유형은 record<USVString,MLOperandDescriptor>입니다.-
이
MLGraph의 모든 입력MLOperand에 대해 입력MLOperand의 이름을 해당MLOperandDescriptor에 매핑합니다. [[outputDescriptors]]의 유형은 record<USVString,MLOperandDescriptor>입니다.-
이
MLGraph의 모든 출력MLOperand에 대해 출력MLOperand의 이름을 해당MLOperandDescriptor에 매핑합니다. [[implementation]]-
사용자 에이전트가 제공하는 기반 구현입니다.
[[isDestroyed]]의 유형은boolean입니다.-
MLGraph.destroy()메서드 단계가 실행되었는지 여부입니다. 파기된 후에는MLGraph를 더 이상 사용할 수 없습니다.
8.4.1. destroy()
destroy()
메서드를 호출하여 그래프와 관련된 모든 리소스를 해제할 수 있습니다.
destroy() 메서드의 단계는 다음과 같습니다.
-
this.
[[isDestroyed]]가 true이면 이 단계를 중단합니다. -
this.
[[isDestroyed]]를 true로 설정합니다. -
이 그래프가 소유한 리소스를 해제 가능한 것으로 표시하도록 this.
[[context]].[[timeline]]에 태스크를 큐에 넣습니다.
참고: 이 그래프를 사용하여 더 이상 워크로드를 큐에 넣을 수 없으므로, 구현은 이전에 제출된 이 그래프를 사용하는 모든 워크로드가 완료되면 이 그래프와 관련하여 추가로 할당된 모든 리소스를 해제할 수 있습니다.
8.5. MLOperandDescriptor
딕셔너리
MLOperandDescriptor는
피연산자의 형상(차원)과 데이터 유형을 설명합니다. 이는 MLGraph의 입력과
상수를 설명하는 데 사용되며, 모든 MLOperand에는
내부 MLOperandDescriptor가
있습니다.
enum {MLInputOperandLayout ,"nchw" };"nhwc" enum {MLOperandDataType ,"float32" ,"float16" ,"int32" ,"uint32" ,"int64" ,"uint64" ,"int8" };"uint8" dictionary {MLOperandDescriptor required MLOperandDataType dataType ;required sequence <[EnforceRange ]unsigned long >shape ; };
dataType, 유형은 MLOperandDataType-
피연산자의 데이터 유형입니다.
shape, 유형은sequence<[EnforceRange] unsigned long>-
피연산자의 차원 목록입니다. 스칼라 피연산자의 경우 비어 있습니다.
MLOperandDescriptor
A가 동일한 하나의 MLOperandDescriptor
B인 것은 A.dataType과
동일한 것이 B.dataType이고
A.shape이
동일한 것은 B.shape인
경우입니다.
MLOperandDataType
dataType과 목록 shape가 주어졌을 때 MLOperandDescriptor를
생성하려면 다음 단계를 실행합니다.
-
descriptor를 새로운
MLOperandDescriptor로 둡니다. -
descriptor.
dataType을 dataType으로 설정합니다. -
descriptor를 반환합니다.
MLOperandDescriptor
desc의 바이트 길이는 다음 단계에서 반환되는 값입니다.
MLOperandDescriptor
desc의 요소 수는 다음 단계에서 반환되는 값입니다.
유효한 차원은
0보다 크고 long
범위에 있는 정수입니다.
구현은 더 작은 상한을 적용할 수 있습니다.
유효한 tensor 수는 0보다 크고 8192 이하인 정수입니다. 구현은 더 작은 상한을 적용할 수 있습니다.
크기가 0인 차원을 지원해야 합니까? [이슈 #391]
MLOperandDescriptor
descriptor가 주어졌을 때 차원을 검사하려면 다음 단계를
실행합니다.
8.6. MLOperand
인터페이스
MLOperand는
연산의 여러 부분을 완전히 구성된 연산으로 조합한 결과로 구성 중인 중간 그래프를 나타냅니다.
예를 들어 MLOperand는
연산에 입력되는 상수 또는 여러 상수를 하나의 연산으로 결합한 결과를
나타낼 수 있습니다. § 7 프로그래밍 모델도 참조하십시오.
[SecureContext ,Exposed =(Window ,Worker )]interface {MLOperand readonly attribute MLOperandDataType dataType ;readonly attribute FrozenArray <unsigned long >shape ; };dictionary {MLOperatorOptions USVString label = ""; };typedef (bigint or unrestricted double )MLNumber ;
MLOperand에는
다음 내부 슬롯이 있습니다.
[[builder]]의 유형은MLGraphBuilder입니다.-
MLOperand와 연관된 builder 객체입니다. [[descriptor]]의 유형은MLOperandDescriptor입니다.-
MLOperand의 descriptor입니다. [[name]]의 유형은 문자열입니다.-
MLOperand의 이름입니다(입력 피연산자에만 해당합니다). [[operator]]의 유형은 연산자입니다.[[constantTensor]]의 유형은MLTensor입니다.-
MLOperand의 tensor입니다(상수 피연산자에만 해당합니다).
MLOperand의
dataType은 해당 [[descriptor]].dataType입니다.
MLOperand의
shape은 해당 [[descriptor]].shape입니다.
MLOperand의
rank는 해당 shape의 크기입니다.
dataType getter 단계는
this의 dataType을 반환합니다.
shape getter 단계는
this의 shape을 반환합니다.
[[builder]]
객체는 MLGraphBuilder()
생성자에 의해 MLContext
객체에 바인딩되므로, MLOperand도
항상 동일한 MLContext
객체에 바인딩됩니다.
연산이 MLOperandDataType의
일부만 지원하는 경우, 위치 인수와 옵션을 모두 포함하여 연산의 각 입력 피연산자에 대한 허용되는 데이터
유형은 MLOperandDataType의
명시적 목록으로 제공되거나, 피연산자의 dataType이 다른 입력 피연산자의 dataType과 같아야 한다는 제약 조건으로 제공되거나,
모든 MLOperandDataType을
허용하기 위해
임의의
유형으로 제공됩니다.
구현은 명시된 것보다 더 적은 피연산자 데이터 유형을 지원할 수 있지만, 최소한 명시된
필수 데이터
유형은 반드시 지원해야 합니다. 현재 Chromium 프로토타입의 ONNX Runtime, LiteRT 및 CoreML 백엔드 전반에서
각 연산에 대한 지원 여부는 MLContext의
opSupportLimits()
메서드를 사용하고 연산에 대응하는 멤버의 dataTypes
값을 검사하여 조회할 수 있습니다.
필수 데이터 유형 집합은 개발자가 이러한 데이터 유형만 사용하도록 모델을 설계하여 상호운용 가능한 콘텐츠를 만들 수 있도록 광범위한 플랫폼에서의 구현 경험을 기반으로 결정되었습니다. 이 명세의 Web Platform Tests는 이 기능 감지 메커니즘을 사용하여 모든 허용되는 데이터 유형에 대해 올바른 동작을 검증하지만, 필수 데이터 유형만 지원해도 통과할 수 있습니다.
연산에 특정 rank의 입력 피연산자가 필요한 경우, 위치 인수와 옵션을 모두 포함하여 연산의 각 입력 피연산자에 대한 허용되는 rank는 명시적인 rank(예: 1), 임의의 차원 수를 허용하는 N, 또는 다른 피연산자와 동일한 rank로 제공됩니다. 입력 피연산자의 shape이 다른 입력 피연산자에 대해 단방향 브로드캐스트 가능해야 하거나 다른 입력 피연산자와 양방향 브로드캐스트 가능해야 하는 경우처럼 더 구체적인 제약 조건도 일반적입니다. 이러한 경우 허용되는 rank는 범위로 나열되며 구체적인 검증은 연산의 단계로 제공됩니다.
구현은 피연산자의 rank에 대해 명시된 것보다 더
제한적인 하한 및/또는 상한을 적용할 수 있지만, 최소한 명시된
필수 rank는 반드시 지원해야 합니다.
현재 Chromium 프로토타입의
ONNX Runtime, LiteRT 및 CoreML 백엔드 전반에서 각 연산에 대한 지원 여부는 MLContext의
opSupportLimits()
메서드를 사용하고 연산에 대응하는 멤버의 rankRange.min
및 rankRange.max
값을 검사하여 조회할 수 있습니다.
필수 rank 집합은 개발자가 이러한 rank의 입력 피연산자로만 구성된 모델을 설계하여 상호운용 가능한 콘텐츠를 만들 수 있도록 광범위한 플랫폼에서의 구현 경험을 기반으로 결정되었습니다.
MLOperatorOptions에는
다음 멤버가 있습니다.
label, 유형은 USVString이며 기본값은""-
MLOperand를 생성하는MLGraphBuilder메서드를 사용하여 연산자를 생성할 때 선택적으로 제공됩니다. 구현은 이 값을 사용하여 연산자의 label을 초기화할 수 있습니다.
참고: label은 자연어
문자열로 사용하기 위한 것이 아닙니다. "mul#1234"와 같이 변수 이름이나 오류 코드와 유사한
언어 독립적인 식별자입니다.
참고: 구현은 개발자가 제공한 label을
사용하여 그래프 구성 중의 동기 오류 및 비동기 build()
메서드 중 발생하는 오류를 포함하여 오류 메시지를 개선하고 디버깅 가능성을 높일 것을 권장합니다.
디버깅 도구, 로그 또는 오류 메시지에 label을
통해 개발자가 제공한 label을 표시할 때 구현은 악의적인 Unicode 시퀀스 삽입과 같은
보안 위험을 방지하도록 출력을 정제해야 합니다(예: 양방향 텍스트
스푸핑 [UTR36], 소스 코드 스푸핑 [UTS55] 및
기타 우려 사항). 예를 들어 구현은 제어 문자(예: U+202A
~ U+202E, U+2066 ~ U+2069)를 이스케이프하거나 필터링하거나 안전한 렌더링 메커니즘을 사용하여 잠재적인
스푸핑을 무력화해야 합니다.
8.6.1. MLOperand
생성
MLOperand
객체는 MLGraphBuilder의
메서드에서 생성되며, 내부적으로 다음 알고리즘을 사용합니다.
MLGraphBuilder
builder와 MLOperandDescriptor
desc가 주어졌을 때 MLOperand를
생성하려면 다음 단계를 실행합니다.
-
realm을 builder의 관련 realm으로 둡니다.
-
operand를 realm의 새로운
MLOperand로 둡니다. -
operand.
[[builder]]를 builder로 설정합니다. -
operand.
[[descriptor]]를 desc로 설정합니다. -
operand를 반환합니다.
MLOperand
operand가 주어졌을 때 MLOperand를
복사하려면 다음 단계를 실행합니다.
-
builder를 operand.
[[builder]]로 둡니다. -
realm을 builder의 관련 realm으로 둡니다.
-
result를 realm의 새로운
MLOperand로 둡니다. -
result.
[[builder]]를 builder로 설정합니다. -
result.
[[descriptor]]를 operand.[[descriptor]]로 설정합니다. -
operand.
[[name]]이 존재하면 result.[[name]]을 operand.[[name]]으로 설정합니다. -
result를 반환합니다.
MLGraphBuilder
builder와 MLOperand
operand가 주어졌을 때 피연산자를 검증하려면, operand.[[builder]]
가 builder이면 true를 반환하고, 그렇지 않으면 false를 반환합니다.
8.6.1.1.
MLNumber
MLNumber는 두 64비트 정수 유형("uint64"
및 "int64")과
32비트 부동 소수점("float32")을
포함하여
임의의 MLOperandDataType일
수 있는
MLOperand의
숫자
옵션 유형을 지정할 때 사용됩니다.
구현은 대응하는 MLOperandDataType에
따라 값을 처리합니다.
예를 들어 clamp(input, options)가
dataType이 "uint32"인
MLOperand와
함께 호출되면,
MLNumber
매개변수는 명시적으로 unsigned long으로
캐스트됩니다.
bigint와
숫자 유형의 union 지원은 [WEBIDL]에서 새로 도입되었으며 구현 지원도 제한적입니다.
프로토타입 구현에서는 이 접근 방식에 대한 의견을 제공할 것을 권장합니다. [whatwg/webidl 이슈 #1388]
8.7. MLTensorDescriptor
딕셔너리
MLTensorDescriptor는
MLTensor의 특성과
기능을 설명합니다.
dictionary :MLTensorDescriptor MLOperandDescriptor {boolean readable =false ;boolean writable =false ; };
readable, 유형은 boolean이며 기본값은false-
readTensor(tensor)또는readTensor(tensor, outputData)를 통해 tensor의 내용을 읽을 수 있는지 여부입니다. writable, 유형은 boolean이며 기본값은false-
writeTensor()를 통해 tensor의 내용을 기록할 수 있는지 여부입니다.
8.8. MLTensor
인터페이스
MLTensor
인터페이스는 MLGraph의
입력 또는 출력으로 사용할 수 있는 tensor를 나타냅니다.
MLTensor을
뒷받침하는
메모리는 이를 생성하는 데 사용된 MLContext와
MLTensorDescriptor의
요구 사항에 따라 구현 정의 방식으로 할당되어야 합니다.
MLTensor의
[[data]]와
관련된 연산은 연관된 MLContext의
[[timeline]]에서
수행됩니다.
MLTensor을
할당하는 방법에 대한 구현 정의 요구 사항에는 메모리가 특정 바이트 정렬에 맞게 할당되거나
특정 메모리 풀에 할당되어야 한다는 등의 제약이 포함될 수 있습니다.
[SecureContext ,Exposed =(Window ,Worker )]interface {MLTensor readonly attribute MLOperandDataType dataType ;readonly attribute FrozenArray <unsigned long >shape ;readonly attribute boolean readable ;readonly attribute boolean writable ;readonly attribute boolean constant ;undefined destroy (); };
MLTensor에는
다음 내부 슬롯이 있습니다.
[[context]]의 유형은MLContext입니다.-
MLTensor와 연관된 컨텍스트입니다. [[descriptor]]의 유형은MLTensorDescriptor입니다.-
MLTensor의 descriptor입니다. [[pendingPromises]]의 유형은Promise의 집합입니다.-
진행 중이며 아직 이행되지 않은
MLContext.readTensor(tensor)메서드 호출에 대응하는 Promise입니다.MLTensor가 파기되면 모든 대기 중인 promise가 거부됩니다. [[isDestroyed]]의 유형은boolean입니다.-
MLTensor.destroy()단계가 실행되었는지 여부입니다. 파기된 후에는MLTensor를 더 이상 사용할 수 없습니다. [[data]]의 유형은 구현 정의 유형입니다.-
MLTensor을 뒷받침하는 바이트입니다. 이 데이터는[[context]].[[timeline]]에서만 접근하거나 수정할 수 있습니다. [[isConstant]]의 유형은boolean입니다.-
MLTensor가 상수 MLTensor 생성에 의해 생성되었는지 여부입니다. [[exportableToGPU]]의 유형은boolean입니다.-
MLTensor가 내보낼 수 있는 MLTensor 생성에 의해 생성되었으며exportToGPU()를 사용하여GPUDevice로 내보낼 수 있는지 여부입니다. [[gpuDevice]]의 유형은GPUDevice또는 null입니다.-
MLTensor를 내보낼 수 있는GPUDevice이며,MLTensor를 내보낼 수 없는 경우 null입니다.[[exportableToGPU]]가 true일 때만 설정됩니다. [[exportedBuffer]]의 유형은GPUBuffer또는 null입니다.-
exportToGPU()의 결과로 현재[[gpuDevice]]에 대여된GPUBuffer이며,MLTensor가 현재 내보내진 상태가 아니면 null입니다.
MLTensor의
dataType은 해당 [[descriptor]]의
dataType입니다.
MLTensor의
shape은 해당 [[descriptor]]의
shape입니다.
dataType getter 단계는
this의 dataType을 반환합니다.
shape getter 단계는
this의 shape을 반환합니다.
readable getter 단계는
this.[[descriptor]].readable을
반환합니다.
writable getter 단계는
this.[[descriptor]].writable을
반환합니다.
constant getter 단계는
this의
[[isConstant]]을
반환합니다.
하나의 MLTensor가
내보낸 상태인 것은 해당 [[exportedBuffer]]가
null이 아닌 경우입니다.
8.8.1. MLTensor
생성
MLTensor는
연관된 MLContext에 의해
생성됩니다.
MLContext
context와 MLTensorDescriptor
descriptor가 주어졌을 때 MLTensor를
생성하려면 다음 단계를 실행합니다.
-
realm을 context의 관련 realm으로 둡니다.
-
tensor를 realm의 새로운
MLTensor로 둡니다. -
tensor.
[[context]]를 context로 설정합니다. -
tensor.
[[descriptor]]를 descriptor로 설정합니다. -
tensor.
[[isDestroyed]]를 false로 설정합니다. -
tensor.
[[isConstant]]를 false로 설정합니다. -
tensor.
[[exportableToGPU]]를 false로 설정합니다. -
tensor.
[[gpuDevice]]를 null로 설정합니다. -
tensor.
[[exportedBuffer]]를 null로 설정합니다. -
tensor를 반환합니다.
MLContext
context, MLTensorDescriptor
descriptor, 그리고 GPUDevice
gpuDevice가 주어졌을 때 내보낼
수 있는 MLTensor를 생성하려면 다음 단계를 실행합니다.
-
tensor를 context와 descriptor가 주어진 상태에서 MLTensor를 생성한 결과로 둡니다.
-
tensor.
[[exportableToGPU]]를 true로 설정합니다. -
tensor.
[[gpuDevice]]를 gpuDevice로 설정합니다. -
tensor를 반환합니다.
MLTensor
tensor가 주어졌을 때 내보낸
MLTensor를 반환하려면 다음 단계를 실행합니다.
-
tensor가 내보내진 상태가 아니면 이 단계를 중단합니다.
-
buffer를 tensor.
[[exportedBuffer]]로 둡니다. -
tensor.
[[exportedBuffer]]를 null로 설정합니다. -
tensor.
[[isDestroyed]]가 true이면 이 단계를 중단합니다. -
다음 단계를 tensor.
[[context]].[[timeline]]에 큐잉합니다.-
다음 단계를 실행하되, tensor.
[[context]]가 손실될 때 중단합니다.
-
사용자 에이전트는 위에서 큐잉된, tensor.[[data]]가
buffer의 내용을 반영하도록 하는 단계가, 이전에 gpuDevice의 GPUQueue에
큐잉되어 buffer에서 읽거나 buffer에 쓰는 모든 연산이 완료되기 전에 실행되지 않도록 반드시 보장해야
합니다.
8.8.2. destroy()
MLTensor과 연관된
리소스를 해제합니다. 이
메서드는 멱등적입니다.
undefined.
destroy() 메서드의 단계는 다음과 같습니다.
-
this.
[[isDestroyed]]를 true로 설정합니다. -
this.
[[pendingPromises]]의 각 promise에 대해 각각:-
promise를 this.
[[pendingPromises]]에서 제거합니다. -
promise를 "
InvalidStateError"DOMException으로 거부합니다.
-
-
다음 단계를 this.
[[context]].[[timeline]]에 큐잉합니다.
참고: 이 tensor를 사용하여 더 이상 연산을 큐에 넣을 수 없으므로, 구현은 이전에 제출된 이 tensor를 사용하는 모든 연산이 완료되면 이 tensor와 관련하여 추가로 할당된 모든 리소스를 해제할 수 있습니다.
8.8.3.
상수 MLTensor
생성
상수 MLTensor는
연관된 MLContext에 의해
생성됩니다.
MLContext
context, MLOperandDescriptor
inputDescriptor가 주어졌을 때 상수
MLTensor를 생성하려면 다음 단계를 실행합니다.
-
realm을 context의 관련 realm으로 둡니다.
-
tensor를 realm의 새로운
MLTensor로 둡니다. -
tensor.
[[context]]를 context로 설정합니다. -
tensorDescriptor를 새로운
MLTensorDescriptor로 둡니다. -
tensorDescriptor.
readable을 false로 설정합니다. -
tensorDescriptor.
writable을 false로 설정합니다. -
tensorDescriptor.
dataType을 inputDescriptor.dataType으로 설정합니다. -
tensor.
[[descriptor]]를 tensorDescriptor로 설정합니다. -
tensor.
[[isDestroyed]]를 false로 설정합니다. -
tensor.
[[isConstant]]를 true로 설정합니다. -
tensor.
[[exportableToGPU]]를 false로 설정합니다. -
tensor.
[[gpuDevice]]를 null로 설정합니다. -
tensor.
[[exportedBuffer]]를 null로 설정합니다. -
tensor를 반환합니다.
8.9. MLGraphBuilder
인터페이스
MLGraphBuilder
인터페이스는 § 2 사용 사례에서 식별된 계산 그래프로
조합할 수 있는 연산 집합을 정의합니다. 또한 그래프 빌드 세션의 중간 상태를 나타냅니다.
typedef record <USVString ,MLOperand >; [MLNamedOperands SecureContext ,Exposed =(Window ,Worker )]interface { // 컨텍스트에서 그래프 빌더를 구성합니다.MLGraphBuilder constructor (MLContext context ); // 그래프 입력용 피연산자를 생성합니다.MLOperand input (USVString name ,MLOperandDescriptor descriptor ); // 그래프 상수용 피연산자를 생성합니다.MLOperand constant (MLOperandDescriptor descriptor ,AllowSharedBufferSource buffer ); // 지정된 유형의 지정된 숫자로부터 스칼라 피연산자를 생성합니다.MLOperand constant (MLOperandDataType dataType ,MLNumber value ); // 지정된 상수 tensor로부터 피연산자를 생성합니다.MLOperand constant (MLTensor tensor ); // 지정된 출력 피연산자까지 그래프를 비동기적으로 컴파일합니다.Promise <MLGraph >build (MLNamedOperands outputs ); };
MLGraphBuilder.build()
메서드는 이를 생성하는 MLContext의 유형에
따라
그래프 빌더 상태를 지정된 출력 피연산자까지 컴파일된 그래프로 컴파일합니다. MLContext의
[[contextType]]이
"default"로 설정된
경우, 컴파일된 그래프는
MLGraph가
반환되기 직전에 초기화됩니다. 이 그래프 초기화 단계는 이후 그래프 실행의 최적 성능을 위해 중요합니다.
일반적으로 그래프에 대한 모든 상수 입력을 전처리하고 이후 그래프 실행 호출을 위해 운영 체제 수준에서 캐시하는
"가중치 전처리"라는 프로세스가 포함됩니다. 초기화 입력은 일반적으로 그래프 구성 중 constant()
메서드를 통해 상수 피연산자로 지정된 상수 가중치 데이터입니다.
MLGraphBuilder에는
다음 내부 슬롯이 있습니다.
[[context]]의 유형은MLContext입니다.-
이
MLGraphBuilder와 연관된MLContext유형의 컨텍스트입니다. [[hasBuilt]]의 유형은boolean입니다.-
MLGraphBuilder.build()가 호출되었는지 여부입니다. 한 번 빌드되면MLGraphBuilder는 더 이상 연산자를 생성하거나MLGraph를 컴파일할 수 없습니다.
8.9.1.
MLGraphBuilder
생성자
-
context:MLContext입니다.MLGraphBuilder와 연관시킬 컨텍스트입니다.
new MLGraphBuilder(context)
생성자의 단계는 다음과 같습니다.
-
this의 관련 전역 객체의 연관된 Document가 사용이 허용되지 않은 webnn 기능이면 "
SecurityError"DOMException을 throw합니다. -
context가 손실된 상태이면 "
InvalidStateError"DOMException을 throw합니다. -
this.
[[context]]를 context로 설정합니다. -
this.
[[hasBuilt]]를 false로 설정합니다.
8.9.2. 입력 피연산자
descriptor를 기반으로 입력으로 사용할 수 있는 이름이 지정된 MLOperand를
생성합니다.
-
name: 입력의 문자열 이름입니다. -
descriptor:MLOperandDescriptor객체입니다.
MLOperand입니다.
input(name, descriptor)
메서드의 단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 "
InvalidStateError"DOMException을 throw합니다. -
this의 그래프의 입력에 있는
MLOperand중 하나라도[[name]]이 name과 같으면TypeError를 throw합니다. -
descriptor가 주어진 상태에서 차원을 검사한 결과가 false이면
TypeError를 throw합니다. -
그래프 연결을 구성합니다.
-
operand를 반환합니다.
MLGraphBuilder
API는 입력 피연산자 없이 MLGraph를 생성할 수 있도록
합니다. 기반 플랫폼이 이를 지원하지 않는 경우 구현은 더미 입력을 추가하거나
상수를 그래프의 입력으로 전달할 수 있습니다.
8.9.3. 상수 피연산자
MLGraphBuilder
메서드에서 사용할 수 있는 상수 MLOperand를 생성합니다.
8.9.3.1. constant(descriptor, buffer)
초기화 데이터를 포함하며 지정된 데이터 유형과 shape을 갖는 상수 MLOperand를
생성합니다.
-
descriptor:MLOperandDescriptor입니다. 출력 tensor의 descriptor입니다. -
buffer:AllowSharedBufferSource입니다. 초기화 데이터를 포함하는 buffer입니다.
MLOperand입니다.
상수
출력 tensor입니다.
constant(descriptor, buffer)
메서드의 단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 "
InvalidStateError"DOMException을 throw합니다. -
descriptor가 주어진 상태에서 차원을 검사한 결과가 false이면
TypeError를 throw합니다. -
buffer와 descriptor가 주어진 상태에서 descriptor를 사용하여 buffer를 검증한 결과가 false이면
TypeError를 throw합니다. -
그래프 연결을 구성합니다.
-
operand를 this와 descriptor가 주어진 상태에서 MLOperand를 생성한 결과로 둡니다.
-
bytes를 buffer가 주어진 상태에서 buffer source가 보유한 바이트의 복사본을 가져온 결과로 둡니다.
-
-
operand를 반환합니다.
8.9.3.2. constant(tensor)
초기화된 데이터를 포함하며 지정된 데이터 유형과 shape을 갖는 상수 MLOperand를
생성합니다.
constant(tensor) 메서드의 단계는
다음과 같습니다.
-
tensor.
[[context]]가 this.[[context]]가 아니면TypeError를 throw합니다. -
tensor.
[[isDestroyed]]가 true이면TypeError를 throw합니다. -
tensor.
[[isConstant]]가 false이면TypeError를 throw합니다. -
this가 빌드할 수 없는 상태이면 "
InvalidStateError"DOMException을 throw합니다. -
그래프 연결을 구성합니다.
-
operand를 this와 tensor.
[[descriptor]]가 주어진 상태에서 MLOperand를 생성한 결과로 둡니다. -
operand.
[[constantTensor]]를 tensor로 설정합니다.
-
-
operand를 반환합니다.
8.9.3.3. constant(dataType, value)
지정된 값과 데이터 유형을 갖는 스칼라 상수 MLOperand를
생성합니다.
"int8"
데이터 유형에 할당되는 경우 등이 있습니다.
-
dataType:MLOperandDataType입니다. -
value:MLNumber입니다. 상수의 값입니다.
MLOperand입니다.
상수
출력입니다.
constant(dataType, value)
메서드의 단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 "
InvalidStateError"DOMException을 throw합니다. -
value를 dataType으로 캐스트한 결과로 설정합니다.
-
descriptor를 dataType과 « »가 주어진 상태에서 MLOperandDescriptor를 생성한 결과로 둡니다.
-
그래프 연결을 구성합니다.
-
operand를 this와 descriptor가 주어진 상태에서 MLOperand를 생성한 결과로 둡니다.
-
-
operand를 반환합니다.
8.9.4. build 메서드
주어진 출력 피연산자까지 구성된 그래프를 계산 그래프로 비동기적으로 빌드합니다.-
outputs:MLNamedOperands입니다. 그래프의 출력이 될MLOperand를 식별합니다.
MLGraph>입니다.
build(outputs) 메서드의 단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 realm에서 "
InvalidStateError"DOMException으로 거부된 새 promise를 반환합니다. -
outputs의 각 name → operand에 대해 각각:
-
operands를 새로운 빈 집합으로 둡니다.
-
operators를 새로운 빈 집합으로 둡니다.
-
inputs를 새로운 빈 집합으로 둡니다.
-
queue가 비어 있지 않은 동안:
-
graph를 realm의 새로운
MLGraph로 둡니다. -
graph.
[[context]]를 this.[[context]]로 설정합니다. -
graph.
[[isDestroyed]]를 false로 설정합니다. -
inputs의 각 operand에 대해 각각:
-
graph.
[[inputDescriptors]][operand.[[name]]] 을 operand.[[descriptor]]로 설정합니다.
-
-
outputs의 각 name → operand에 대해 각각:
-
graph.
[[outputDescriptors]][name] 을 operand.[[descriptor]]로 설정합니다.
-
-
this.
[[hasBuilt]]를 true로 설정합니다. -
promise를 realm의 새 promise로 둡니다.
-
다음 단계를 graph.
[[context]].[[timeline]]에 큐잉합니다.-
다음 단계를 실행하되, graph.
[[context]]가 손실될 때 중단합니다.-
graphImpl을 this의 그래프를 operands, operators, inputs, outputs의 값, 그리고 graph.
[[context]].[[powerPreference]]및 graph.[[context]].[[accelerated]]와 함께, 기반 플랫폼에서 해석할 수 있는 구현 정의 형식으로 변환한 결과로 둡니다. -
이전 단계가 실패하면 global을 사용하여 ML 태스크를 큐에 넣어 promise를 "
OperationError"DOMException으로 거부하고 이 단계를 중단합니다. -
graph.
[[implementation]]을 graphImpl로 설정합니다. -
global을 사용하여 ML 태스크를 큐에 넣어 promise를 graph로 이행합니다.
-
-
중단된 경우, global을 사용하여 ML 태스크를 큐에 넣어 promise를 "
InvalidStateError"DOMException으로 거부합니다.
-
-
promise를 반환합니다.
참고: 입력 피연산자 또는 상수 피연산자를 그래프 output으로
지정하면 오류가 발생합니다. 이는 일반적으로 API를 잘못 사용하는 경우이기 때문입니다. 호출자는
identity()
연산자를 추가하여 이를 우회할 수 있습니다.
8.9.5. argMin/argMax 연산
축을 따라 모든 입력 값의 최솟값 또는 최댓값의 인덱스 위치를 반환합니다. 동률인 경우 반환 값의 선택은 구현에 따라 달라집니다.dictionary :MLArgMinMaxOptions MLOperatorOptions {boolean keepDimensions =false ;MLOperandDataType outputDataType = "int32"; };partial interface MLGraphBuilder {MLOperand argMin (MLOperand input , [EnforceRange ]unsigned long axis ,optional MLArgMinMaxOptions options = {});MLOperand argMax (MLOperand input , [EnforceRange ]unsigned long axis ,optional MLArgMinMaxOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits argMin ;MLSingleInputSupportLimits argMax ; };
MLArgMinMaxOptions에는
다음 멤버가 있습니다.
keepDimensions, 유형은 boolean이며 기본값은false-
true이면 축소된 차원을 크기 1로 유지합니다.
outputDataType, 유형은 MLOperandDataType이며 기본값은"int32"-
MLOperandDataType입니다. 출력 데이터 유형입니다.
-
input:MLOperand입니다. 입력 N차원 tensor입니다. -
axis: 축소할 차원입니다. 값은 [0, N-1] 범위여야 하며, 여기서 N은 입력 tensor의 rank입니다. -
options: 선택적MLArgMinMaxOptions입니다. 연산의 선택적 매개변수입니다.
반환: MLOperand입니다.
keepDimensions
가 true이면 input의
rank와 같은 rank를 가지며, keepDimensions
가 false이면 input의
rank - 1인 출력 N차원
tensor입니다. 값은
outputDataType
유형이어야 하며 [0, N-1] 범위여야 합니다. 여기서 N은 axis로
지정한 입력 차원의 크기입니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
input
| 모든 유형 | "float32",
"float16",
"int32"
| 1에서 N까지 | 1에서 5까지 |
| 출력 | "int32",
"int64"
| "int32"
| N | 0에서 5까지 |
MLOpSupportLimits에는
argMin()
및 argMax()에
대해 다음 멤버가 있습니다.
argMin, 유형은 MLSingleInputSupportLimits-
argMin()연산자의 지원 제한입니다. argMax, 유형은 MLSingleInputSupportLimits-
argMax()연산자의 지원 제한입니다.
문자열
op, MLOperand
input, unsigned long
axis, 그리고 MLArgMinMaxOptions
options가 주어졌을 때 argMin/argMax 연산을 생성하려면
다음 단계를 실행합니다.
-
단언: op는 "argMin", "argMax" 중 하나입니다.
-
this가 빌드할 수 없는 상태이면 "
InvalidStateError"DOMException을 throw합니다. -
this와 input을 사용하여 피연산자를 검증한 결과가 false이면
TypeError를 throw합니다. -
options.
outputDataType이 출력 tensor의 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름)TypeError를 throw합니다. -
input의 shape[axis]가 options.
outputDataType의 최댓값보다 크면TypeError를 throw합니다. -
outputShape를 input의 shape, « axis », 그리고 options.
keepDimensions가 주어진 상태에서 축소 출력 크기를 계산한 결과로 둡니다. 실패가 반환되면TypeError를 throw합니다. -
desc를 options.
outputDataType과 outputShape가 주어진 상태에서 MLOperandDescriptor를 생성한 결과로 둡니다. -
그래프 연결을 구성합니다.
-
operator를 options가 주어진 op 연산에 대한 연산자로 둡니다.
-
output을 this와 desc가 주어진 상태에서 MLOperand를 생성한 결과로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
다음 argMin/argMax 알고리즘이 지원됩니다.
argMin(input, axis, options)
메서드의 단계는 다음과 같습니다.
-
output을 "argMin", input, axis, 그리고 options가 주어진 상태에서 argMin/argMax 연산을 생성한 결과로 둡니다.
-
output을 반환합니다.
argMax(input, axis, options)
메서드의 단계는 다음과 같습니다.
-
output을 "argMax", input, axis, 그리고 options가 주어진 상태에서 argMin/argMax 연산을 생성한 결과로 둡니다.
-
output을 반환합니다.
8.9.6. batchNormalization
[Batch-Normalization]을 사용하여 입력 tensor의 값을 정규화합니다. 각 입력 특성에 대해 모델을 학습하는 동안 해당 특성의 평균값과 분산값을 배치 차원의 모든 샘플에 걸쳐 계산합니다. 이후 모델 추론 중에 이러한 평균값과 분산값이 이 연산에 제공됩니다.dictionary :MLBatchNormalizationOptions MLOperatorOptions {MLOperand scale ;MLOperand bias ; [EnforceRange ]unsigned long axis = 1;double epsilon = 1e-5; };partial interface MLGraphBuilder {MLOperand batchNormalization (MLOperand input ,MLOperand mean ,MLOperand variance ,optional MLBatchNormalizationOptions options = {}); };dictionary {MLBatchNormalizationSupportLimits MLTensorLimits input ;MLTensorLimits mean ;MLTensorLimits variance ;MLTensorLimits scale ;MLTensorLimits bias ;MLTensorLimits output ; };partial dictionary MLOpSupportLimits {MLBatchNormalizationSupportLimits batchNormalization ; };
MLBatchNormalizationOptions에는
다음 멤버가 있습니다.
scale, 유형은 MLOperandbias, 유형은 MLOperandaxis, 유형은 unsigned long이며 기본값은1-
평균값과 분산값이 대응하는 입력 shape의 특성 수 차원에 대한 인덱스입니다. 값은 [0, N-1] 범위여야 하며, 여기서 N은 입력 tensor의 rank입니다. 기본값은 1이며,
"nchw"데이터 레이아웃의 채널("c") 차원에 해당합니다. epsilon, 유형은 double이며 기본값은1e-5-
0으로 나누어 발생하는 계산 오류를 방지하기 위한 작은 값입니다.
-
input:MLOperand입니다. 입력 N차원 tensor입니다. -
mean:MLOperand입니다. 배치 전체에서 입력 특성의 평균값을 담은 1차원 tensor를 지정합니다. 해당 크기는axis가 나타내는 입력 차원의 크기와 같습니다. -
variance:MLOperand입니다. 배치 전체에서 입력 특성의 분산값을 담은 1차원 tensor이며, 해당 크기는axis가 나타내는 입력 차원의 크기와 같습니다. -
options: 선택적MLBatchNormalizationOptions입니다. 연산의 선택적 매개변수를 지정합니다.
반환: MLOperand입니다.
input과
동일한 shape을 갖는 배치 정규화된 N차원 tensor입니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
input
| "float32",
"float16"
| "float32",
"float16"
| 1에서 N까지 | 3에서 5까지 |
mean
| input과
동일한 유형
| "float32",
"float16"
| 1 | 1 |
variance
| input과
동일한 유형
| "float32",
"float16"
| 1 | 1 |
scale
| input과
동일한 유형
| "float32",
"float16"
| 1 | 1 |
bias
| input과
동일한 유형
| "float32",
"float16"
| 1 | 1 |
| 출력 | input과
동일한 유형
| "float32",
"float16"
| input과
동일한 rank
| 3에서 5까지 |
MLBatchNormalizationSupportLimits에는
다음 멤버가 있습니다.
input, 유형은 MLTensorLimits-
입력 피연산자에 대한
MLTensorLimits입니다. mean, 유형은 MLTensorLimits-
mean 피연산자에 대한
MLTensorLimits입니다. variance, 유형은 MLTensorLimits-
variance 피연산자에 대한
MLTensorLimits입니다. scale, 유형은 MLTensorLimits-
scale 피연산자에 대한
MLTensorLimits입니다. bias, 유형은 MLTensorLimits-
bias 피연산자에 대한
MLTensorLimits입니다. output, 유형은 MLTensorLimits-
출력 피연산자에 대한
MLTensorLimits입니다.
MLOpSupportLimits에는
batchNormalization()에
대해 다음 멤버가 있습니다.
batchNormalization, 유형은 MLBatchNormalizationSupportLimits-
batchNormalization()연산자의 지원 제한입니다.
batchNormalization(input, mean, variance, options)
메서드의 단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 "
InvalidStateError"DOMException을 throw합니다. -
this와 input, mean, variance, options.
scale(해당 값이 존재하는 경우), 그리고 options.bias(해당 값이 존재하는 경우) 중 하나를 사용하여 피연산자를 검증한 결과가 false이면TypeError를 throw합니다. -
input의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름)
TypeError를 throw합니다. -
options.
axis가 0부터 input의 rank까지의 범위에 포함되지 않으면(상한 제외)TypeError를 throw합니다. -
mean의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름)
TypeError를 throw합니다. -
mean의 shape이 « input의 shape[options.
axis] »와 같지 않으면TypeError를 throw합니다. -
variance의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름)
TypeError를 throw합니다. -
variance의 shape이 « input의 shape[options.
axis] »와 같지 않으면TypeError를 throw합니다. -
options.
epsilon을 options.epsilon을 input의 dataType으로 캐스트한 결과로 설정합니다. -
그래프 연결을 구성합니다.
-
operator를 input, mean, variance, 그리고 options가 주어진 "batchNormalization" 연산에 대한 연산자로 둡니다.
-
output을 this와 input.
[[descriptor]]가 주어진 상태에서 MLOperand를 생성한 결과로 둡니다. -
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input, mean, 그리고 variance로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
입력 tensor가 "nchw"
레이아웃의 4차원인 경우, 사용자 에이전트에는 일반적으로 더 효율적인 구현이 있지만
이 연산의 동작을 다음과 같이 다른 연산을 사용하여 일반적으로 에뮬레이션할 수 있습니다. 기반 플랫폼에서
연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로 사용할 수 있습니다.
function batchNormalization( builder, input, mean, variance, options) { const shape= [ 1 , input. shape[ options. axis], 1 , 1 ]; return builder. add( builder. mul( builder. reshape( options. scale, shape), builder. div( builder. sub( input, builder. reshape( mean, shape)), builder. sqrt( builder. add( builder. reshape( variance, shape), builder. constant( input. dataType, options. epsilon))))), builder. reshape( options. bias, shape)); }
8.9.7. cast
입력 tensor의 각 요소를 대상 데이터 유형으로 캐스트합니다.partial interface MLGraphBuilder {MLOperand cast (MLOperand input ,MLOperandDataType dataType ,optional MLOperatorOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits cast ; };
-
input:MLOperand입니다. 입력 N차원 tensor입니다. -
dataType:MLOperandDataType입니다. 대상 데이터 유형입니다. -
options:MLOperatorOptions입니다. 연산의 선택적 매개변수를 지정합니다.
반환: MLOperand입니다.
각 요소가 대상 데이터 유형으로 캐스트된 input과
동일한 shape의 N차원 tensor입니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
input
| 모든 유형 | "float32",
"float16",
"int32",
"int8",
"uint8"
| N | 0에서 5까지 |
| 출력 | 모든 유형 | "float32",
"float16",
"int32",
"int8",
"uint8"
| input과
동일한 rank
| 0에서 5까지 |
MLOpSupportLimits에는
cast()에
대해 다음 멤버가 있습니다.
cast, 유형은 MLSingleInputSupportLimits-
cast()연산자의 지원 제한입니다.
MLOperandDataType
간의
캐스팅은 다음 표에 따라 일부 경우에는 명세되어 있고 다른 경우에는 구현
정의입니다.
| 대상 유형 입력 유형 |
"float32",
"float16"
|
"int32",
"uint32",
"int64",
"uint64",
"int8",
"uint8"
|
|---|---|---|
"float32",
"float16"
|
범위 내이면 가장 가까운 표현 가능한 값입니다.
범위를 벗어나면 +/-Infinity입니다. |
범위 내이면 잘립니다.
범위를 벗어나면 구현 정의입니다. |
"int32",
"uint32",
"int64",
"uint64",
"int8",
"uint8"
|
범위 내이면 가장 가까운 표현 가능한 값입니다.
범위를 벗어나면 +/-Infinity입니다. |
범위 내이면 동일한 값입니다.
범위를 벗어나면 하위 N비트를 대상 유형으로 재해석하며, 부호 있는 유형에는 2의 보수를 가정합니다. |
참고: 예를 들어 "int8"의
-1을 "uint8"로
캐스트하면 255가 되도록 명세되어 있습니다. 그러나 "float32"의
-1을 "uint8"로
캐스트하는 것은 구현 정의입니다.
cast(input, dataType, options)
메서드의 단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 "
InvalidStateError"DOMException을 throw합니다. -
this와 input을 사용하여 피연산자를 검증한 결과가 false이면
TypeError를 throw합니다. -
dataType이 출력 tensor의 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름)
TypeError를 throw합니다. -
그래프 연결을 구성합니다.
-
operator를 dataType과 options가 주어진 "cast" 연산에 대한 연산자로 둡니다.
-
output을 input이 주어진 상태에서 MLOperand를 복사한 결과로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
8.9.8. clamp
최솟값과 최댓값으로 지정된 범위 내에서 입력 tensor의 각 요소를 제한합니다.dictionary :MLClampOptions MLOperatorOptions {MLNumber minValue ;MLNumber maxValue ; };partial interface MLGraphBuilder {MLOperand clamp (MLOperand input ,optional MLClampOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits clamp ; };
MLClampOptions에는
다음 멤버가 있습니다.
minValue, 유형은 MLNumber-
범위의 최솟값입니다. 지정하지 않으면 범위의 하한에 대해 제한이 수행되지 않습니다.
maxValue, 유형은 MLNumber-
범위의 최댓값입니다. 지정하지 않으면 범위의 상한에 대해 제한이 수행되지 않습니다.
-
input:MLOperand입니다. 입력 tensor입니다. -
options: 선택적MLClampOptions입니다. 연산의 선택적 매개변수입니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
input
| 모든 유형 | "float32",
"float16"
| N | 0에서 5까지 |
| 출력 | input과
동일한 유형
| "float32",
"float16"
| input과
동일한 rank
| 0에서 5까지 |
MLOpSupportLimits에는
clamp()에
대해 다음 멤버가 있습니다.
clamp, 유형은 MLSingleInputSupportLimits-
clamp()연산자의 지원 제한입니다.
clamp(input, options) 메서드의
단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 "
InvalidStateError"DOMException을 throw합니다. -
this와 input을 사용하여 피연산자를 검증한 결과가 false이면
TypeError를 throw합니다. -
minValue를 지정된 경우 options.
minValue로, 그렇지 않으면 Infinity로 둡니다. -
options.
minValue를 minValue를 input의 dataType으로 캐스트한 결과로 설정합니다. -
maxValue를 지정된 경우 options.
maxValue로, 그렇지 않으면 -Infinity로 둡니다. -
options.
maxValue를 maxValue를 input의 dataType으로 캐스트한 결과로 설정합니다. -
options.
minValue가 options.maxValue보다 크면TypeError를 throw합니다. -
그래프 연결을 구성합니다.
-
output을 input이 주어진 상태에서 MLOperand를 복사한 결과로 둡니다.
-
operator를 options가 주어진 "clamp" 연산에 대한 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
사용자 에이전트에는 일반적으로 더 효율적인 구현이 있지만, 이 연산의 동작은 다음과 같이 다른 연산을 사용하여 일반적으로 에뮬레이션할 수 있습니다. 기반 플랫폼에서 연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로 사용할 수 있습니다.
function clamp( builder, input, options) { if ( options. minValue=== undefined ) { if ( options. maxValue=== undefined ) { return input; } else { return builder. min( input, builder. constant( input. dataType, options. maxValue)); } } else { if ( options. maxValue=== undefined ) { return builder. max( input, builder. constant( input. dataType, options. minValue)); } else { return builder. min( builder. max( input, builder. constant( input. dataType, options. minValue)), builder. constant( input. dataType, options. maxValue)); } } }
8.9.9. concat
주어진 축을 따라 입력 tensor를 연결합니다.partial interface MLGraphBuilder {MLOperand concat (sequence <MLOperand >inputs , [EnforceRange ]unsigned long axis ,optional MLOperatorOptions options = {}); };dictionary {MLConcatSupportLimits MLTensorLimits inputs ;MLTensorLimits output ; };partial dictionary MLOpSupportLimits {MLConcatSupportLimits concat ; };
-
inputs: sequence<MLOperand>입니다. 모든 입력 tensor는 연결할 차원의 크기를 제외하고 동일한 shape을 가져야 합니다. -
axis:unsigned long스칼라입니다. 입력을 연결할 축입니다. 값은 [0, N-1] 범위여야 하며, 여기서 N은 입력 tensor의 rank입니다. -
options:MLOperatorOptions입니다. 연산의 선택적 매개변수를 지정합니다.
반환: MLOperand입니다.
모든 입력을 axis를
따라 연결한 tensor입니다.
출력 tensor는 모든 입력이 연결된 차원을
제외하고 동일한 shape을 갖습니다. 해당 차원의 크기는
같은 차원에 대한 모든 입력 크기의 합으로 계산됩니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
inputs의
항목
| 모든 유형 | "float32",
"float16",
"int32"
| 1에서 N까지 | 1에서 5까지 |
| 출력 | inputs의
항목과 동일한 유형
| "float32",
"float16",
"int32"
| inputs의
항목과 동일한 rank
| 1에서 5까지 |
MLConcatSupportLimits에는
다음 멤버가 있습니다.
inputs, 유형은 MLTensorLimits-
모든 입력 피연산자에 대한
MLTensorLimits입니다. output, 유형은 MLTensorLimits-
출력 피연산자에 대한
MLTensorLimits입니다.
MLOpSupportLimits에는
concat()에
대해 다음 멤버가 있습니다.
concat, 유형은 MLConcatSupportLimits-
concat()연산자의 지원 제한입니다.
concat(inputs, axis, options)
메서드의 단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 "
InvalidStateError"DOMException을 throw합니다. -
this와 inputs의 임의의 항목을 사용하여 피연산자를 검증한 결과가 false이면
TypeError를 throw합니다. -
inputs의 크기가 유효한 tensor 수가 아니면
TypeError를 throw합니다. -
first를 inputs[0]으로 둡니다.
-
desc를 first의 dataType과 first의 shape이 주어진 상태에서 MLOperandDescriptor를 생성한 결과로 둡니다.
-
그래프 연결을 구성합니다.
-
output을 this와 desc가 주어진 상태에서 MLOperand를 생성한 결과로 둡니다.
-
operator를 inputs, axis, 그리고 options가 주어진 "concat" 연산에 대한 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 inputs로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
8.9.10. conv2d
4차원 입력 및 필터 tensor가 주어졌을 때 2차원 컨볼루션을 계산합니다.enum {MLConv2dFilterOperandLayout ,"oihw" ,"hwio" ,"ohwi" };"ihwo" dictionary :MLConv2dOptions MLOperatorOptions {sequence <[EnforceRange ]unsigned long >padding ;sequence <[EnforceRange ]unsigned long >strides ;sequence <[EnforceRange ]unsigned long >dilations ; [EnforceRange ]unsigned long groups = 1;MLInputOperandLayout inputLayout = "nchw";MLConv2dFilterOperandLayout filterLayout = "oihw";MLOperand bias ; };partial interface MLGraphBuilder {MLOperand conv2d (MLOperand input ,MLOperand filter ,optional MLConv2dOptions options = {}); };dictionary {MLConv2dSupportLimits MLTensorLimits input ;MLTensorLimits filter ;MLTensorLimits bias ;MLTensorLimits output ; };partial dictionary MLOpSupportLimits {MLConv2dSupportLimits conv2d ; };
MLConv2dOptions에는
다음 멤버가 있습니다.
padding, 유형은sequence<[EnforceRange] unsigned long>-
길이가 4인 목록입니다: [beginningHeight, endingHeight, beginningWidth, endingWidth]. 컨볼루션 입력의 각 공간 차원의 시작과 끝에 추가되는 행과 열을 지정합니다. 기본값은 [0, 0, 0, 0]입니다.
strides, 유형은sequence<[EnforceRange] unsigned long>-
길이가 2인 목록입니다: [strideHeight, strideWidth]. 컨볼루션 입력의 각 공간 차원에 대한 슬라이딩 윈도우의 stride를 지정합니다. 기본값은 [1, 1]입니다.
dilations, 유형은sequence<[EnforceRange] unsigned long>-
길이가 2인 목록입니다: [dilationHeight, dilationWidth]. 컨볼루션 필터(커널)에 적용되는 각 공간 차원의 dilation 계수를 지정합니다. 기본값은 [1, 1]입니다.
groups, 유형은 unsigned long이며 기본값은1-
입력 채널과 출력 채널이 나뉘는 그룹 수입니다.
inputLayout, 유형은 MLInputOperandLayout이며 기본값은"nchw"-
입력 및 출력 tensor의 레이아웃 형식을 다음과 같이 지정합니다.
filterLayout, 유형은 MLConv2dFilterOperandLayout이며 기본값은"oihw"-
필터 tensor의 레이아웃 형식을 다음과 같이 지정합니다.
bias, 유형은 MLOperand-
컨볼루션 결과에 값을 더할 [outputChannels] shape의 추가 1차원 tensor입니다.
-
input:MLOperand입니다. 입력 4차원 tensor입니다. 논리적 shape은inputLayout값에 따라 해석됩니다. -
filter:MLOperand입니다. 필터 4차원 tensor입니다. 논리적 shape은filterLayout및groups값에 따라 해석됩니다. -
options:MLConv2dOptions입니다. 연산의 선택적 매개변수입니다.
반환: MLOperand입니다.
컨볼루션 결과를 포함하는 출력 4차원 tensor입니다. 출력 shape은
inputLayout에
따라 해석됩니다.
더 구체적으로 "nchw"
입력 레이아웃에서 출력 tensor의 공간 차원 또는 마지막 두 차원의 크기는
다음과 같이 계산할 수 있습니다.
outputSize = 1 + (inputSize - (filterSize - 1) * dilation - 1 + beginningPadding + endingPadding) / stride
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
input
| "float32",
"float16"
| "float32",
"float16"
| 4 | 4 |
filter
| input과
동일한 유형
| "float32",
"float16"
| 4 | 4 |
bias
| input과
동일한 유형
| "float32",
"float16"
| 1 | 1 |
| 출력 | input과
동일한 유형
| "float32",
"float16"
| 4 | 4 |
MLConv2dSupportLimits에는
다음 멤버가 있습니다.
input, 유형은 MLTensorLimits-
입력 피연산자에 대한
MLTensorLimits입니다. filter, 유형은 MLTensorLimits-
filter 피연산자에 대한
MLTensorLimits입니다. bias, 유형은 MLTensorLimits-
bias 피연산자에 대한
MLTensorLimits입니다. output, 유형은 MLTensorLimits-
출력 피연산자에 대한
MLTensorLimits입니다.
MLOpSupportLimits에는
conv2d()에
대해 다음 멤버가 있습니다.
conv2d, 유형은 MLConv2dSupportLimits-
conv2d()연산자의 지원 제한입니다.
groups
= inputChannels = outputChannels이고 필터 tensor의 shape은 "oihw"
레이아웃의 경우 [options.groups, 1, height, width],
"hwio"
레이아웃의 경우 [height, width, 1, options.groups],
"ohwi"
레이아웃의 경우 [options.groups, height, width, 1], 그리고 "ihwo"
레이아웃의 경우 [1, height, width, options.groups]입니다.
부호 없는 정수 inputSize, filterSize, beginningPadding, endingPadding, stride 및 dilation이 주어졌을 때 conv 출력 크기를 계산하려면 다음 단계를 수행합니다. 숫자를 반환합니다.
-
effectiveFilterSize를 ( filterSize - 1 ) * dilation + 1로 둡니다.
-
outputSize를 ( inputSize - effectiveFilterSize + beginningPadding + endingPadding ) / stride + 1로 둡니다.
-
outputSize를 반환합니다.
부호 없는 정수 inputHeight, inputWidth, filterHeight 및 filterWidth, 부호 없는 정수 4개로 이루어진 목록 padding, 부호 없는 정수 2개로 이루어진 목록 strides, 그리고 부호 없는 정수 2개로 이루어진 목록 dilations가 주어졌을 때 conv2d 출력 크기를 계산하려면 다음 단계를 수행합니다. 숫자 2개로 이루어진 목록을 반환합니다.
-
outputHeight를 inputHeight, filterHeight, padding[0], padding[1], strides[0] 및 dilations[0]이 주어진 상태에서 conv 출력 크기를 계산한 결과로 둡니다.
-
outputWidth를 inputWidth, filterWidth, padding[2], padding[3], strides[1] 및 dilations[1]이 주어진 상태에서 conv 출력 크기를 계산한 결과로 둡니다.
-
« outputHeight, outputWidth »를 반환합니다.
conv2d(input, filter, options)
메서드의 단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 "
InvalidStateError"DOMException을 throw합니다. -
this와 input, filter, 그리고 options.
bias(해당 값이 존재하는 경우) 중 하나를 사용하여 피연산자를 검증한 결과가 false이면TypeError를 throw합니다. -
input의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름)
TypeError를 throw합니다. -
filter의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름)
TypeError를 throw합니다. -
출력 shape을 계산합니다.
-
inputShape을 input의 shape으로 둡니다.
-
options.
inputLayout에 따라 분기합니다. -
filterShape을 filter의 shape으로 둡니다.
-
options.
filterLayout에 따라 분기합니다."hwio"-
« filterHeight, filterWidth, filterInputChannels, outputChannels »를 filterShape으로 둡니다.
"ohwi"-
« outputChannels, filterHeight, filterWidth, filterInputChannels »를 filterShape으로 둡니다.
"ihwo"-
« filterInputChannels, filterHeight, filterWidth, outputChannels »를 filterShape으로 둡니다.
"oihw"-
« outputChannels, filterInputChannels, filterHeight, filterWidth »를 filterShape으로 둡니다.
-
inputChannels % options.
groups가 0이 아니면TypeError를 throw합니다. -
그렇지 않고 inputChannels / options.
groups가 filterInputChannels와 같지 않으면TypeError를 throw합니다. -
outputChannels % options.
groups가 0이 아니면TypeError를 throw합니다. -
« outputHeight, outputWidth »를 inputHeight, inputWidth, filterHeight, filterWidth, options.
padding, options.strides, 그리고 options.dilations가 주어진 상태에서 conv2d 출력 크기를 계산한 결과로 둡니다. -
outputHeight를 floor( outputHeight )로 설정합니다.
-
outputWidth를 floor( outputWidth )로 설정합니다.
-
outputHeight 또는 outputWidth 중 하나라도 유효한 차원이 아니면
TypeError를 throw합니다. -
options.
inputLayout에 따라 분기합니다. -
desc를 input의 dataType과 outputShape이 주어진 상태에서 MLOperandDescriptor를 생성한 결과로 둡니다.
-
-
그래프 연결을 구성합니다.
-
output을 this와 desc가 주어진 상태에서 MLOperand를 생성한 결과로 둡니다.
-
operator를 options과 filter가 주어진 "conv2d" 연산에 대한 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input과 filter로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
8.9.11. convTranspose2d
4차원 입력 및 필터 tensor가 주어졌을 때 2차원 전치 컨볼루션을 계산합니다.enum {MLConvTranspose2dFilterOperandLayout ,"iohw" ,"hwoi" };"ohwi" dictionary :MLConvTranspose2dOptions MLOperatorOptions {sequence <[EnforceRange ]unsigned long >padding ;sequence <[EnforceRange ]unsigned long >strides ;sequence <[EnforceRange ]unsigned long >dilations ;sequence <[EnforceRange ]unsigned long >outputPadding ;sequence <[EnforceRange ]unsigned long >outputSizes ; [EnforceRange ]unsigned long groups = 1;MLInputOperandLayout inputLayout = "nchw";MLConvTranspose2dFilterOperandLayout filterLayout = "iohw";MLOperand bias ; };partial interface MLGraphBuilder {MLOperand convTranspose2d (MLOperand input ,MLOperand filter ,optional MLConvTranspose2dOptions options = {}); };partial dictionary MLOpSupportLimits {MLConv2dSupportLimits convTranspose2d ; };
MLConvTranspose2dOptions에는
다음 멤버가 있습니다.
padding, 유형은sequence<[EnforceRange] unsigned long>-
길이가 4인 목록입니다: [beginningHeight, endingHeight, beginningWidth, endingWidth]. 컨볼루션 입력의 각 공간 차원의 시작과 끝에 추가되는 행과 열을 지정합니다. 기본값은 [0, 0, 0, 0]입니다.
strides, 유형은sequence<[EnforceRange] unsigned long>-
길이가 2인 목록입니다: [strideHeight, strideWidth]. 컨볼루션 입력의 각 공간 차원에 대한 슬라이딩 윈도우의 stride를 지정합니다. 기본값은 [1, 1]입니다.
dilations, 유형은sequence<[EnforceRange] unsigned long>-
길이가 2인 목록입니다: [dilationHeight, dilationWidth]. 컨볼루션 필터(커널)에 적용되는 각 공간 차원의 dilation 계수를 지정합니다. 기본값은 [1, 1]입니다.
outputPadding, 유형은sequence<[EnforceRange] unsigned long>-
길이가 2인 목록입니다. 출력 tensor의 각 공간 차원에 적용되는 padding 값을 지정합니다.
strides값이 1보다 큰 경우 전치 컨볼루션의 출력 tensor shape을 명확하게 결정하기 위해 명시적인 padding 값이 필요합니다.이 값은 필요한 경우 출력 shape을 명확하게 결정하는 데만 사용되며, 반드시 어떤 padding 값이 출력 tensor에 기록되도록 하는 것은 아닙니다.
기본값은 [0, 0]입니다.
outputSizes, 유형은sequence<[EnforceRange] unsigned long>-
길이가 2인 목록입니다. 출력 tensor의 마지막 두 차원의 크기를 지정합니다. 출력 크기가 명시적으로 지정되면
outputPadding의 출력 padding 값은 무시됩니다.지정하지 않으면 출력 크기가 자동으로 계산됩니다.
groups, 유형은 unsigned long이며 기본값은1-
입력 채널과 출력 채널이 나뉘는 그룹 수입니다.
inputLayout, 유형은 MLInputOperandLayout이며 기본값은"nchw"-
입력 및 출력 tensor의 레이아웃 형식을 다음과 같이 지정합니다.
filterLayout, 유형은 MLConvTranspose2dFilterOperandLayout이며 기본값은"iohw"-
필터 tensor의 레이아웃 형식을 다음과 같이 지정합니다.
bias, 유형은 MLOperand-
컨볼루션 결과에 값을 더할 [outputChannels] shape의 추가 1차원 tensor입니다.
-
input:MLOperand입니다. 입력 4차원 tensor입니다. 논리적 shape은inputLayout값에 따라 해석됩니다. -
filter:MLOperand입니다. 필터 4차원 tensor입니다. 논리적 shape은filterLayout및groups값에 따라 해석됩니다. -
options: 선택적MLConvTranspose2dOptions입니다.
반환: MLOperand입니다.
전치 컨볼루션 결과를 포함하는 출력 4차원 tensor입니다. 출력 shape은
inputLayout에
따라 해석됩니다.
더 구체적으로 outputSizes가
명시적으로 지정되지 않은 경우, 출력 tensor의 공간 차원 값을 다음과 같이 계산하려면 outputPadding이
필요합니다.
outputSize = (inputSize - 1) * stride + (filterSize - 1) * dilation + 1 - beginningPadding - endingPadding + outputPadding
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
input
| "float32",
"float16"
| "float32",
"float16"
| 4 | 4 |
filter
| input과
동일한 유형
| "float32",
"float16"
| 4 | 4 |
bias
| input과
동일한 유형
| "float32",
"float16"
| 1 | 1 |
| 출력 | input과
동일한 유형
| "float32",
"float16"
| 4 | 4 |
MLOpSupportLimits에는
convTranspose2d()에
대해 다음 멤버가 있습니다.
convTranspose2d, 유형은 MLConv2dSupportLimits-
convTranspose2d()연산자의 지원 제한입니다.
부호 없는 정수 inputSize, filterSize, beginningPadding, endingPadding, stride 및 dilation이 주어졌을 때 convtranspose 출력 크기를 계산하려면 다음 단계를 수행합니다. 숫자를 반환합니다.
-
effectiveFilterSize를 ( filterSize - 1 ) * dilation + 1로 둡니다.
-
outputSize를 ( inputSize - 1 ) * stride + effectiveFilterSize - beginningPadding - endingPadding으로 둡니다.
-
outputSize를 반환합니다.
convTranspose2d(input, filter, options)
메서드의 단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 "
InvalidStateError"DOMException을 throw합니다. -
this와 input, filter, 그리고 options.
bias(해당 값이 존재하는 경우) 중 하나를 사용하여 피연산자를 검증한 결과가 false이면TypeError를 throw합니다. -
input의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름)
TypeError를 throw합니다. -
filter의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름)
TypeError를 throw합니다. -
options.
outputPadding이 존재하지 않으면 목록 « 0, 0 »으로 설정합니다. -
그렇지 않고 options.
outputPadding의 크기가 2가 아니면TypeError를 throw합니다. -
options.
outputSizes가 존재하면: -
그렇지 않으면:
-
options.
outputPadding[0] 이 options.strides[0]보다 크거나 같거나, options.outputPadding[1] 이 options.strides[1]보다 크거나 같으면TypeError를 throw합니다.
-
-
출력 shape을 계산합니다.
-
inputShape을 input의 shape으로 둡니다.
-
options.
inputLayout에 따라 분기합니다. -
filterShape을 filter의 shape으로 둡니다.
-
options.
filterLayout에 따라 분기합니다. -
inputChannels가 filterInputChannels와 같지 않으면
TypeError를 throw합니다. -
outputChannels를 filterOutputChannels * options.
groups로 둡니다. -
calculatedOutputHeight를 inputHeight, filterHeight, padding[0], padding[1], strides[0] 및 dilations[0]이 주어진 상태에서 convtranspose 출력 크기를 계산한 결과로 둡니다.
-
calculatedOutputWidth를 inputWidth, filterWidth, padding[2], padding[3], strides[1] 및 dilations[1]이 주어진 상태에서 convtranspose 출력 크기를 계산한 결과로 둡니다.
-
options.
outputSizes가 존재하면:-
« outputHeight, outputWidth »를 options.
outputSizes로 둡니다. -
outputHeight가 calculatedOutputHeight보다 작거나, outputHeight가 calculatedOutputHeight + strides[0]보다 크거나 같으면
TypeError를 throw합니다. -
outputWidth가 calculatedOutputWidth보다 작거나, outputWidth가 calculatedOutputWidth + strides[1]보다 크거나 같으면
TypeError를 throw합니다.
-
-
그렇지 않으면:
-
outputHeight를 calculatedOutputHeight + options.
outputPadding[0]으로 둡니다. -
outputWidth를 calculatedOutputWidth + options.
outputPadding[1]로 둡니다.
-
-
outputHeight 또는 outputWidth 중 하나라도 유효한 차원이 아니면
TypeError를 throw합니다. -
options.
inputLayout에 따라 분기합니다. -
desc를 input의 dataType과 outputShape이 주어진 상태에서 MLOperandDescriptor를 생성한 결과로 둡니다.
-
-
그래프 연결을 구성합니다.
-
output을 this와 desc가 주어진 상태에서 MLOperand를 생성한 결과로 둡니다.
-
operator를 options과 filter가 주어진 "convTranspose2d" 연산에 대한 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input과 filter로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
8.9.12. cumulativeSum
주어진 축을 따라 일련의 값의 누적합을 계산하며, 현재 값을 포함하거나 제외할 수 있습니다.dictionary :MLCumulativeSumOptions MLOperatorOptions {boolean exclusive =false ;boolean reversed =false ; };partial interface MLGraphBuilder {MLOperand cumulativeSum (MLOperand input ,unsigned long axis ,optional MLCumulativeSumOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits cumulativeSum ; };
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
input
| "float32",
"float16",
"int32",
"uint32",
"int64",
"uint64"
| "float32",
"float16",
"int32"
| 1에서 N까지 | 1에서 5까지 |
| 출력 | input과
동일한 유형
| "float32",
"float16",
"int32"
| input과
동일한 rank
| 1에서 5까지 |
MLCumulativeSumOptions에는
다음 멤버가 있습니다.
exclusive, 유형은 boolean이며 기본값은false-
출력에 현재 값을 포함할지 제외할지 여부이며, 각각 포함 누적합 또는 배타 누적합 [Prefix-sum]을 의미합니다. 입력 [1,2,3,4]가 주어지면 포함 합산은 [1,3,6,10]을 출력하고 배타 합산은 [0,1,3,6]을 출력합니다. 기본값은 포함입니다.
reversed, 유형은 boolean이며 기본값은false-
활성 축을 따라 합산 방향을 반대로 하여 높은 좌표에서 낮은 좌표로 시작할지 여부입니다. 입력 [1,2,3,4]가 주어지면 포함 순방향 합산은 [1,3,6,10]을 출력하고 포함 역방향 합산은 [10,9,7,4]을 출력합니다. 기본값은 순방향입니다.
-
input:MLOperand입니다. 입력 tensor입니다. -
axis:unsigned long스칼라입니다. 합산을 수행할 축입니다. 값은 [0, N-1] 범위여야 하며, 여기서 N은input의 rank입니다. -
options:MLCumulativeSumOptions입니다. 연산의 선택적 매개변수를 지정합니다.
반환:
MLOpSupportLimits에는
cumulativeSum()에
대해 다음 멤버가 있습니다.
cumulativeSum, 유형은 MLSingleInputSupportLimits-
cumulativeSum()연산자의 지원 제한입니다.
cumulativeSum(input, axis, options)
메서드의 단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 "
InvalidStateError"DOMException을 throw합니다. -
this와 input을 사용하여 피연산자를 검증한 결과가 false이면
TypeError를 throw합니다. -
input의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름)
TypeError를 throw합니다. -
그래프 연결을 구성합니다.
-
output을 input이 주어진 상태에서 MLOperand를 복사한 결과로 둡니다.
-
operator를 "cumulativeSum" 연산 및 options에 대한 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
8.9.13. 요소별 이항 연산
두 입력 tensor의 요소별 이항 덧셈, 뺄셈, 곱셈, 나눗셈, 거듭제곱, 최댓값 및 최솟값을 계산합니다.연산은 [numpy-broadcasting-rule]에 따라 브로드캐스트됩니다. 입력 tensor는 양방향 브로드캐스트 가능해야 합니다. 출력 tensor의 rank는 입력 tensor의 최대 rank입니다. 출력 tensor의 각 차원에 대해 그 크기는 입력 tensor에서 해당 차원을 따른 최대 크기입니다.
partial interface MLGraphBuilder {MLOperand add (MLOperand a ,MLOperand b ,optional MLOperatorOptions options = {});MLOperand sub (MLOperand a ,MLOperand b ,optional MLOperatorOptions options = {});MLOperand mul (MLOperand a ,MLOperand b ,optional MLOperatorOptions options = {});MLOperand div (MLOperand a ,MLOperand b ,optional MLOperatorOptions options = {});MLOperand max (MLOperand a ,MLOperand b ,optional MLOperatorOptions options = {});MLOperand min (MLOperand a ,MLOperand b ,optional MLOperatorOptions options = {});MLOperand pow (MLOperand a ,MLOperand b ,optional MLOperatorOptions options = {}); };partial dictionary MLOpSupportLimits {MLBinarySupportLimits add ;MLBinarySupportLimits sub ;MLBinarySupportLimits mul ;MLBinarySupportLimits div ;MLBinarySupportLimits max ;MLBinarySupportLimits min ;MLBinarySupportLimits pow ; };
-
a:MLOperand입니다. 첫 번째 입력 tensor입니다. -
b:MLOperand입니다. 두 번째 입력 tensor입니다. -
options:MLOperatorOptions입니다. 연산의 선택적 매개변수를 지정합니다.
반환: MLOperand입니다.
두 입력 tensor에 대한 요소별 이항 연산의
결과를 포함하는 출력 tensor입니다.
-
add: 두 입력 tensor의 값을 요소별로 더합니다.
-
sub: 첫 번째 입력 tensor의 값에서 두 번째 입력 tensor의 값을 요소별로 뺍니다.
-
mul: 두 입력 tensor의 값을 요소별로 곱합니다.
-
div: 첫 번째 입력 tensor의 값을 두 번째 tensor의 값으로 요소별로 나눕니다. 정수 유형은 0 방향으로 잘립니다.
-
max: 두 입력 tensor의 값 중 더 큰 값을 요소별로 선택합니다.
-
min: 두 입력 tensor의 값 중 더 작은 값을 요소별로 선택합니다.
-
pow: 첫 번째 입력 tensor의 값을 두 번째 입력 tensor의 값만큼 거듭제곱하여 요소별로 계산합니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
a
| 모든 유형 | "float32",
"float16",
"int32"
| N | 0에서 5까지 |
b
| a와
동일한 유형
| "float32",
"float16",
"int32"
| N | 0에서 5까지 |
| 출력 | a와
동일한 유형
| "float32",
"float16",
"int32"
| N | 0에서 5까지 |
MLOpSupportLimits에는
요소별 이항 연산에 대해 다음 멤버가 있습니다.
add, 유형은 MLBinarySupportLimits-
add()연산자의 지원 제한입니다. sub, 유형은 MLBinarySupportLimits-
sub()연산자의 지원 제한입니다. mul, 유형은 MLBinarySupportLimits-
mul()연산자의 지원 제한입니다. div, 유형은 MLBinarySupportLimits-
div()연산자의 지원 제한입니다. max, 유형은 MLBinarySupportLimits-
max()연산자의 지원 제한입니다. min, 유형은 MLBinarySupportLimits-
min()연산자의 지원 제한입니다. pow, 유형은 MLBinarySupportLimits-
pow()연산자의 지원 제한입니다.
문자열
op, MLOperand
a, MLOperand
b, 그리고 MLOperatorOptions
options가 주어졌을 때 요소별
이항 연산을 생성하려면 다음 단계를 실행합니다.
-
단언: op는 "add", "sub", "mul", "div", "max", "min", "pow" 중 하나입니다.
-
this가 빌드할 수 없는 상태이면 "
InvalidStateError"DOMException을 throw합니다. -
다음 피연산자 검증을 this와 a 및 b 중 하나로 수행한 결과가 false이면, 예외를 발생시킵니다:
TypeError. -
outputShape을 a의 shape과 b의 shape을 양방향 브로드캐스트한 결과로 둡니다.
-
descriptor를 a의 dataType과 outputShape이 주어진 상태에서 MLOperandDescriptor를 생성한 결과로 둡니다.
-
그래프 연결을 구성합니다.
-
output을 this와 descriptor가 주어진 상태에서 MLOperand를 생성한 결과로 둡니다.
-
operator를 a, b, 그리고 options가 주어진 op 연산에 대한 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 a와 b로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
요소별 이항 연산 알고리즘은 다음과 같이 요소별 이항 연산을 생성하는 단계를 호출합니다.
add(a, b, options)
메서드의 단계는 다음과 같습니다.
-
output을 "add", a, b, 그리고 options가 주어진 상태에서 요소별 이항 연산을 생성한 결과로 둡니다.
-
output을 반환합니다.
sub(a, b, options)
메서드의 단계는 다음과 같습니다.
-
output을 "sub", a, b, 그리고 options가 주어진 상태에서 요소별 이항 연산을 생성한 결과로 둡니다.
-
output을 반환합니다.
mul(a, b, options)
메서드의 단계는 다음과 같습니다.
-
output을 "mul", a, b, 그리고 options가 주어진 상태에서 요소별 이항 연산을 생성한 결과로 둡니다.
-
output을 반환합니다.
div(a, b, options)
메서드의 단계는 다음과 같습니다.
-
output을 "div", a, b, 그리고 options가 주어진 상태에서 요소별 이항 연산을 생성한 결과로 둡니다.
-
output을 반환합니다.
max(a, b, options)
메서드의 단계는 다음과 같습니다.
-
output을 "max", a, b, 그리고 options가 주어진 상태에서 요소별 이항 연산을 생성한 결과로 둡니다.
-
output을 반환합니다.
min(a, b, options)
메서드의 단계는 다음과 같습니다.
-
output을 "min", a, b, 그리고 options가 주어진 상태에서 요소별 이항 연산을 생성한 결과로 둡니다.
-
output을 반환합니다.
pow(a, b, options)
메서드의 단계는 다음과 같습니다.
-
output을 "pow", a, b, 그리고 options가 주어진 상태에서 요소별 이항 연산을 생성한 결과로 둡니다.
-
output을 반환합니다.
8.9.14. 요소별 논리 연산
입력 tensor를 요소별로 비교하고 비교 결과에 대해 0(false) 또는 1(true) 값을 갖는"uint8"
tensor를 반환합니다. 단일 피연산자 연산의 경우 해당 연산의 논리
결과를 반환합니다.
여러 피연산자 연산의 경우, 연산은 브로드캐스트되며 [numpy-broadcasting-rule]을 따릅니다. 입력 텐서는 양방향 브로드캐스트 가능해야 합니다. 출력 텐서의 랭크는 입력 텐서의 최대 랭크입니다. 출력 텐서의 각 차원에 대해 그 크기는 입력 텐서의 해당 차원을 따른 최대 크기입니다.
partial interface MLGraphBuilder {MLOperand equal (MLOperand a ,MLOperand b ,optional MLOperatorOptions options = {});MLOperand notEqual (MLOperand a ,MLOperand b ,optional MLOperatorOptions options = {});MLOperand greater (MLOperand a ,MLOperand b ,optional MLOperatorOptions options = {});MLOperand greaterOrEqual (MLOperand a ,MLOperand b ,optional MLOperatorOptions options = {});MLOperand lesser (MLOperand a ,MLOperand b ,optional MLOperatorOptions options = {});MLOperand lesserOrEqual (MLOperand a ,MLOperand b ,optional MLOperatorOptions options = {});MLOperand logicalNot (MLOperand a ,optional MLOperatorOptions options = {});MLOperand logicalAnd (MLOperand a ,MLOperand b ,optional MLOperatorOptions options = {});MLOperand logicalOr (MLOperand a ,MLOperand b ,optional MLOperatorOptions options = {});MLOperand logicalXor (MLOperand a ,MLOperand b ,optional MLOperatorOptions options = {});MLOperand isNaN (MLOperand a ,optional MLOperatorOptions options = {});MLOperand isInfinite (MLOperand a ,optional MLOperatorOptions options = {}); };dictionary {MLLogicalNotSupportLimits MLTensorLimits a ;MLTensorLimits output ; };partial dictionary MLOpSupportLimits {MLBinarySupportLimits equal ;MLBinarySupportLimits notEqual ;MLBinarySupportLimits greater ;MLBinarySupportLimits greaterOrEqual ;MLBinarySupportLimits lesser ;MLBinarySupportLimits lesserOrEqual ;MLLogicalNotSupportLimits logicalNot ;MLBinarySupportLimits logicalAnd ;MLBinarySupportLimits logicalOr ;MLBinarySupportLimits logicalXor ;MLLogicalNotSupportLimits isNaN ;MLLogicalNotSupportLimits isInfinite ; };
-
a:MLOperand입니다. 첫 번째 입력 tensor입니다. -
b:MLOperand입니다. 지정된 경우 두 번째 입력 tensor입니다. -
options:MLOperatorOptions입니다. 연산의 선택적 매개변수를 지정합니다.
반환: MLOperand입니다.
두 입력 tensor의 요소별 비교 결과를 포함하는 출력 tensor입니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
a
| 모든 유형 | "float32",
"float16",
"int32"
| N | 0에서 5까지 |
b
| a와
동일한 유형
| "float32",
"float16",
"int32"
| N | 0에서 5까지 |
| 출력 | "uint8"
| "uint8"
| N | 0에서 5까지 |
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
a
| "uint8"
| "uint8"
| N | 0에서 5까지 |
| 출력 | "uint8"
| "uint8"
| N | 0에서 5까지 |
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
a
| "uint8"
| "uint8"
| N | 0에서 5까지 |
b
| a와
동일한 유형
| "uint8"
| N | 0에서 5까지 |
| 출력 | "uint8"
| "uint8"
| N | 0에서 5까지 |
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
a
| 모든 유형 | "float32",
"float16"
| N | 0에서 5까지 |
| 출력 | "uint8"
| "uint8"
| N | 0에서 5까지 |
MLLogicalNotSupportLimits에는
다음 멤버가 있습니다.
a, 유형은 MLTensorLimits-
a 피연산자에 대한
MLTensorLimits입니다. output, 유형은 MLTensorLimits-
출력 피연산자에 대한
MLTensorLimits입니다.
MLOpSupportLimits에는
요소별 논리 연산에 대해 다음 멤버가 있습니다.
equal, 유형은 MLBinarySupportLimits-
equal()연산자의 지원 제한입니다. notEqual, 유형은 MLBinarySupportLimits-
notEqual()연산자의 지원 제한입니다. greater, 유형은 MLBinarySupportLimits-
greater()연산자의 지원 제한입니다. greaterOrEqual, 유형은 MLBinarySupportLimits-
greaterOrEqual()연산자의 지원 제한입니다. lesser, 유형은 MLBinarySupportLimits-
lesser()연산자의 지원 제한입니다. lesserOrEqual, 유형은 MLBinarySupportLimits-
lesserOrEqual()연산자의 지원 제한입니다. logicalNot, 유형은 MLLogicalNotSupportLimits-
logicalNot()연산자의 지원 제한입니다. logicalAnd, 유형은 MLBinarySupportLimits-
logicalAnd()연산자의 지원 제한입니다. logicalOr, 유형은 MLBinarySupportLimits-
logicalOr()연산자의 지원 제한입니다. logicalXor, 유형은 MLBinarySupportLimits-
logicalXor()연산자의 지원 제한입니다. isNaN, 유형은 MLLogicalNotSupportLimits-
isNaN()연산자의 지원 제한입니다. isInfinite, 유형은 MLLogicalNotSupportLimits-
isInfinite()연산자의 지원 제한입니다.
-
equal: 두 입력 tensor의 값이 같은지 요소별로 비교합니다.
-
notEqual: 두 입력 tensor의 값이 같지 않은지 요소별로 비교합니다.
-
greater: 첫 번째 입력 tensor의 값이 더 큰지 요소별로 비교합니다.
-
greaterOrEqual: 첫 번째 입력 tensor의 값이 더 크거나 같은지 요소별로 비교합니다.
-
lesser: 첫 번째 입력 tensor의 값이 더 작은지 요소별로 비교합니다.
-
lesserOrEqual: 첫 번째 입력 tensor의 값이 더 작거나 같은지 요소별로 비교합니다.
-
logicalNot: 입력 tensor의 값을 요소별로 0 또는 1로 반전합니다. 구체적으로 입력 값이 0이 아니면 0으로 반전합니다. 반대로 입력 값이 0이면 1로 반전합니다.
-
logicalAnd: 두 입력 tensor의 논리 and를 요소별로 계산하며, 0이 아닌 모든 값을 true로 간주하고 0 또는 1의 요소를 반환합니다.
-
logicalOr: 두 입력 tensor의 논리 or를 요소별로 계산하며, 0이 아닌 모든 값을 true로 간주하고 0 또는 1의 요소를 반환합니다.
-
logicalXor: 두 입력 tensor의 논리 xor를 요소별로 계산하며, 0이 아닌 모든 값을 true로 간주하고 0 또는 1의 요소를 반환합니다.
-
isNaN: 입력 tensor의 값이 유효하지 않은 숫자 표현 (NaN)인지 요소별로 검사하며, NaN에는 1을 반환하고 그렇지 않으면 0을 반환합니다.
-
isInfinite: 입력 tensor의 값이 무한대인지 요소별로 검사하며, 양의 무한대 또는 음의 무한대에는 1을 반환하고 그렇지 않으면 0을 반환합니다.
greaterOrEqual()
및 lesserOrEqual()
연산은 각각 logicalNot(),
lesser(),
그리고 greater()
연산으로 각각 구현할 수 있지만(즉 builder.greaterOrEqual(a, b)는
builder.logicalNot(builder.lesser(a, b))입니다), NaN 사례를 처리하고
이중 비교를 피하여 성능을 높이기 위해 별도로 정의되어 있습니다.
문자열
op, MLOperand
a, 선택적 MLOperand
b, 그리고 MLOperatorOptions
options가 주어졌을 때 요소별
논리 연산을 생성하려면 다음 단계를 실행합니다.
-
단언: op는 "equal", "notEqual", "greater", "greaterOrEqual", "lesser", "lesserOrEqual", "logicalNot", "logicalAnd", "logicalOr", "logicalXor", "isNaN", "isInfinite" 중 하나입니다.
-
this가 빌드할 수 없는 상태이면 "
InvalidStateError"DOMException을 throw합니다. -
op가 "logicalNot", "logicalAnd", "logicalOr", "logicalXor" 중 하나이면:
-
op가 "isNaN", "isInfinite" 중 하나이면:
-
b가 전달되면:
-
그렇지 않으면:
-
descriptor를
"uint8"과 outputShape이 주어진 상태에서 MLOperandDescriptor를 생성한 결과로 둡니다. -
그래프 연결을 구성합니다.
-
output을 this와 descriptor가 주어진 상태에서 MLOperand를 생성한 결과로 둡니다.
-
operator를 a와 (b가 전달된 경우) b, 그리고 options가 주어진 op 연산에 대한 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 a와 (b가 전달된 경우) b로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
요소별 논리 연산 알고리즘은 다음과 같이 요소별 논리 연산을 생성하는 단계를 호출합니다.
equal(a, b, options)
메서드의 단계는 다음과 같습니다.
-
output을 "equal", a, b, 그리고 options가 주어진 상태에서 요소별 논리 연산을 생성한 결과로 둡니다.
-
output을 반환합니다.
notEqual(a, b, options)
메서드의 단계는 다음과 같습니다.
-
output을 "notEqual", a, b, 그리고 options가 주어진 상태에서 요소별 논리 연산을 생성한 결과로 둡니다.
-
output을 반환합니다.
greater(a, b, options)
메서드의 단계는 다음과 같습니다.
-
output을 "greater", a, b, 그리고 options가 주어진 상태에서 요소별 논리 연산을 생성한 결과로 둡니다.
-
output을 반환합니다.
greaterOrEqual(a, b, options)
메서드의 단계는 다음과 같습니다.
-
output을 "greaterOrEqual", a, b, 그리고 options가 주어진 상태에서 요소별 논리 연산을 생성한 결과로 둡니다.
-
output을 반환합니다.
lesser(a, b, options)
메서드의 단계는 다음과 같습니다.
-
output을 "lesser", a, b, 그리고 options가 주어진 상태에서 요소별 논리 연산을 생성한 결과로 둡니다.
-
output을 반환합니다.
lesserOrEqual(a, b, options)
메서드의 단계는 다음과 같습니다.
-
output을 "lesserOrEqual", a, b, 그리고 options가 주어진 상태에서 요소별 논리 연산을 생성한 결과로 둡니다.
-
output을 반환합니다.
logicalNot(a, options)
메서드의 단계는 다음과 같습니다.
-
output을 "logicalNot", a, 그리고 options가 주어진 상태에서 요소별 논리 연산을 생성한 결과로 둡니다.
-
output을 반환합니다.
logicalAnd(a, b, options)
메서드의 단계는 다음과 같습니다.
-
output을 "logicalAnd", a, b, 그리고 options가 주어진 상태에서 요소별 논리 연산을 생성한 결과로 둡니다.
-
output을 반환합니다.
logicalOr(a, b, options)
메서드의 단계는 다음과 같습니다.
-
output을 "logicalOr", a, b, 그리고 options가 주어진 상태에서 요소별 논리 연산을 생성한 결과로 둡니다.
-
output을 반환합니다.
logicalXor(a, b, options)
메서드의 단계는 다음과 같습니다.
-
output을 "logicalXor", a, b, 그리고 options가 주어진 상태에서 요소별 논리 연산을 생성한 결과로 둡니다.
-
output을 반환합니다.
isNaN(a, options) 메서드의
단계는 다음과 같습니다.
-
output을 "isNaN", a, 그리고 options가 주어진 상태에서 요소별 논리 연산을 생성한 결과로 둡니다.
-
output을 반환합니다.
isInfinite(a, options)
메서드의 단계는 다음과 같습니다.
-
output을 "isInfinite", a, 그리고 options가 주어진 상태에서 요소별 논리 연산을 생성한 결과로 둡니다.
-
output을 반환합니다.
8.9.15. 요소별 단항 연산
입력 tensor에 대해 요소별 단항 연산을 계산합니다.partial interface MLGraphBuilder {MLOperand abs (MLOperand input ,optional MLOperatorOptions options = {});MLOperand ceil (MLOperand input ,optional MLOperatorOptions options = {});MLOperand cos (MLOperand input ,optional MLOperatorOptions options = {});MLOperand erf (MLOperand input ,optional MLOperatorOptions options = {});MLOperand exp (MLOperand input ,optional MLOperatorOptions options = {});MLOperand floor (MLOperand input ,optional MLOperatorOptions options = {});MLOperand identity (MLOperand input ,optional MLOperatorOptions options = {});MLOperand log (MLOperand input ,optional MLOperatorOptions options = {});MLOperand neg (MLOperand input ,optional MLOperatorOptions options = {});MLOperand reciprocal (MLOperand input ,optional MLOperatorOptions options = {});MLOperand roundEven (MLOperand input ,optional MLOperatorOptions options = {});MLOperand sin (MLOperand input ,optional MLOperatorOptions options = {});MLOperand sign (MLOperand input ,optional MLOperatorOptions options = {});MLOperand sqrt (MLOperand input ,optional MLOperatorOptions options = {});MLOperand tan (MLOperand input ,optional MLOperatorOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits abs ;MLSingleInputSupportLimits ceil ;MLSingleInputSupportLimits cos ;MLSingleInputSupportLimits erf ;MLSingleInputSupportLimits exp ;MLSingleInputSupportLimits floor ;MLSingleInputSupportLimits identity ;MLSingleInputSupportLimits log ;MLSingleInputSupportLimits neg ;MLSingleInputSupportLimits reciprocal ;MLSingleInputSupportLimits roundEven ;MLSingleInputSupportLimits sin ;MLSingleInputSupportLimits sign ;MLSingleInputSupportLimits sqrt ;MLSingleInputSupportLimits tan ; };
-
input:MLOperand입니다. 입력 tensor입니다. -
options:MLOperatorOptions입니다. 연산의 선택적 매개변수를 지정합니다.
반환: MLOperand입니다.
입력 tensor에 대한 요소별 단항 연산의
결과를 포함하는 출력 tensor입니다. 출력
tensor의 shape은 입력 tensor의 shape과 같습니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
input
| "float32",
"float16",
"int64",
"int32",
"int8"
| "float32",
"float16",
"int32"
| N | 0에서 5까지 |
| 출력 | input과
동일한 유형
| "float32",
"float16",
"int32"
| input과
동일한 rank
| 0에서 5까지 |
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
input
| "float32",
"float16"
| "float32",
"float16"
| N | 0에서 5까지 |
| 출력 | input과
동일한 유형
| "float32",
"float16"
| input과
동일한 rank
| 0에서 5까지 |
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
input
| 모든 유형 | "float32",
"float16",
"int32"
| N | 0에서 5까지 |
| 출력 | input과
동일한 유형
| "float32",
"float16",
"int32"
| input과
동일한 rank
| 0에서 5까지 |
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
input
| "float32",
"float16",
"int64",
"int32",
"int8"
| "float32",
"float16",
"int32"
| N | 0에서 5까지 |
| 출력 | input과
동일한 유형
| "float32",
"float16",
"int32"
| input과
동일한 rank
| 0에서 5까지 |
MLOpSupportLimits에는
요소별 단항 연산에 대해 다음 멤버가 있습니다.
abs, 유형은 MLSingleInputSupportLimits-
abs()연산자의 지원 제한입니다. ceil, 유형은 MLSingleInputSupportLimits-
ceil()연산자의 지원 제한입니다. cos, 유형은 MLSingleInputSupportLimits-
cos()연산자의 지원 제한입니다. erf, 유형은 MLSingleInputSupportLimits-
erf()연산자의 지원 제한입니다. exp, 유형은 MLSingleInputSupportLimits-
exp()연산자의 지원 제한입니다. floor, 유형은 MLSingleInputSupportLimits-
floor()연산자의 지원 제한입니다. identity, 유형은 MLSingleInputSupportLimits-
identity()연산자의 지원 제한입니다. log, 유형은 MLSingleInputSupportLimits-
log()연산자의 지원 제한입니다. neg, 유형은 MLSingleInputSupportLimits-
neg()연산자의 지원 제한입니다. reciprocal, 유형은 MLSingleInputSupportLimits-
reciprocal()연산자의 지원 제한입니다. roundEven, 유형은 MLSingleInputSupportLimits-
roundEven()연산자의 지원 제한입니다. sin, 유형은 MLSingleInputSupportLimits-
sin()연산자의 지원 제한입니다. sign, 유형은 MLSingleInputSupportLimits-
sign()연산자의 지원 제한입니다. sqrt, 유형은 MLSingleInputSupportLimits-
sqrt()연산자의 지원 제한입니다. tan, 유형은 MLSingleInputSupportLimits-
tan()연산자의 지원 제한입니다.
-
abs: 입력 tensor의 절댓값을 요소별로 계산합니다.
-
ceil: 입력 tensor의 올림값을 요소별로 계산합니다.
-
cos: 입력 tensor의 코사인을 요소별로 계산합니다.
-
erf: 입력 tensor의 오류 함수 [Error-Function]를 요소별로 계산합니다.
-
exp: 입력 tensor의 지수 함수를 요소별로 계산합니다.
-
floor: 입력 tensor의 내림값을 요소별로 계산합니다.
-
identity: 입력 tensor의 값을 출력 tensor로 요소별로 복사합니다.
-
log: 입력 tensor의 자연로그를 요소별로 계산합니다.
-
neg: 입력 tensor의 수치적 음수 값을 요소별로 계산합니다.
-
reciprocal: 입력 tensor의 역수를 요소별로 계산합니다.
-
roundEven: 입력 tensor의 중간값을 가장 가까운 짝수 값으로 요소별로 반올림합니다. (예: [0.1, 0.9, 1.1, 1.9, -3.5, -2.5, -1.5, 1.5, 2.5, 3.5]는 [0.0, 1.0, 1.0, 2.0, -4.0, -2.0, -2.0, 2.0, 2.0, 4.0]이 됩니다).
-
sin: 입력 tensor의 사인을 요소별로 계산합니다.
-
sign: 입력 tensor의 부호(-1, 0, 1)를 요소별로 계산하며, > 0이면 1, < 0이면 -1, 그렇지 않으면 0을 반환합니다.
-
sqrt: 입력 tensor의 제곱근을 요소별로 계산합니다.
-
tan: 입력 tensor의 탄젠트를 요소별로 계산합니다.
문자열
op, MLOperand
input, 선택적 목록 allowedDataTypes, 그리고 options가 주어졌을 때 요소별
단항 연산을 생성하려면 다음
단계를 실행합니다.
-
단언: op는 "abs", "ceil", "cos", "erf", "exp", "floor", "identity", "log", "neg", "reciprocal", "roundEven", "sin", "sign", "sqrt", "tan" 중 하나입니다.
-
this가 빌드할 수 없는 상태이면 "
InvalidStateError"DOMException을 throw합니다. -
this와 input을 사용하여 피연산자를 검증한 결과가 false이면
TypeError를 throw합니다. -
allowedDataTypes가 주어지고 input의 dataType을 포함하지 않으면
TypeError를 throw합니다. -
그래프 연결을 구성합니다.
-
output을 input이 주어진 상태에서 MLOperand를 복사한 결과로 둡니다.
-
operator를 options가 주어진 op 연산에 대한 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
요소별 단항 연산 알고리즘은 다음과 같이 요소별 단항 연산을 생성하는 단계를 호출합니다.
abs(input, options) 메서드의
단계는 다음과 같습니다.
ceil(input, options) 메서드의
단계는 다음과 같습니다.
-
output을 "ceil", input, «
"float32","float16"», 그리고 options가 주어진 상태에서 요소별 단항 연산을 생성한 결과로 둡니다. -
output을 반환합니다.
cos(input, options) 메서드의
단계는 다음과 같습니다.
-
output을 "cos", input, «
"float32","float16"», 그리고 options가 주어진 상태에서 요소별 단항 연산을 생성한 결과로 둡니다. -
output을 반환합니다.
erf(input, options) 메서드의
단계는 다음과 같습니다.
-
output을 "erf", input, «
"float32","float16"», 그리고 options가 주어진 상태에서 요소별 단항 연산을 생성한 결과로 둡니다. -
output을 반환합니다.
exp(input, options) 메서드의
단계는 다음과 같습니다.
-
output을 "exp", input, «
"float32","float16"», 그리고 options가 주어진 상태에서 요소별 단항 연산을 생성한 결과로 둡니다. -
output을 반환합니다.
floor(input, options) 메서드의
단계는 다음과 같습니다.
-
output을 "floor", input, «
"float32","float16"», 그리고 options가 주어진 상태에서 요소별 단항 연산을 생성한 결과로 둡니다. -
output을 반환합니다.
identity(input, options)
메서드의 단계는 다음과 같습니다.
-
output을 "identity", input, 그리고 options가 주어진 상태에서 요소별 단항 연산을 생성한 결과로 둡니다.
-
output을 반환합니다.
log(input, options) 메서드의
단계는 다음과 같습니다.
-
output을 "log", input, «
"float32","float16"», 그리고 options가 주어진 상태에서 요소별 단항 연산을 생성한 결과로 둡니다. -
output을 반환합니다.
neg(input, options) 메서드의
단계는 다음과 같습니다.
reciprocal(input, options)
메서드의 단계는 다음과 같습니다.
-
output을 "reciprocal", input, «
"float32","float16"», 그리고 options가 주어진 상태에서 요소별 단항 연산을 생성한 결과로 둡니다. -
output을 반환합니다.
roundEven(input, options)
메서드의 단계는 다음과 같습니다.
-
output을 "roundEven", input, «
"float32","float16"», 그리고 options가 주어진 상태에서 요소별 단항 연산을 생성한 결과로 둡니다. -
output을 반환합니다.
sin(input, options) 메서드의
단계는 다음과 같습니다.
-
output을 "sin", input, «
"float32","float16"», 그리고 options가 주어진 상태에서 요소별 단항 연산을 생성한 결과로 둡니다. -
output을 반환합니다.
sign(input, options) 메서드의
단계는 다음과 같습니다.
sqrt(input, options) 메서드의
단계는 다음과 같습니다.
-
output을 "sqrt", input, «
"float32","float16"», 그리고 options가 주어진 상태에서 요소별 단항 연산을 생성한 결과로 둡니다. -
output을 반환합니다.
tan(input, options) 메서드의
단계는 다음과 같습니다.
-
output을 "tan", input, «
"float32","float16"», 그리고 options가 주어진 상태에서 요소별 단항 연산을 생성한 결과로 둡니다. -
output을 반환합니다.
사용자 에이전트에는 일반적으로 더 효율적인 구현이 있지만, sign()
연산의 동작은 다음과 같이 다른 연산을 사용하여 일반적으로 에뮬레이션할 수 있습니다. 기반
플랫폼에서 연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로
사용할 수 있습니다.
function sign( builder, input, options) { const zero= builder. constant( input. dataType, 0 ); const positiveOne= builder. constant( input. dataType, 1 ); const negativeOne= builder. constant( input. dataType, - 1 ); return builder. where( builder. greater( input, zero), positiveOne, builder. where( builder. lesser( input, zero), negativeOne, zero)); }
8.9.16. dequantizeLinear
scale과 zero-point 바이어스를 사용하여 정수 텐서를 부동 소수점 텐서로 역양자화하며, 여기서output = (input - zeroPoint) * scale입니다. scale
및 zeroPoint
텐서는 input
텐서보다 작을 수 있으며, 이는 블록 단위 브로드캐스트 가능하기 때문입니다.
partial interface MLGraphBuilder {MLOperand dequantizeLinear (MLOperand input ,MLOperand scale ,MLOperand zeroPoint ,optional MLOperatorOptions options = {}); };dictionary {MLQuantizeDequantizeLinearSupportLimits MLTensorLimits input ;MLTensorLimits scale ;MLTensorLimits zeroPoint ;MLTensorLimits output ; };partial dictionary MLOpSupportLimits {MLQuantizeDequantizeLinearSupportLimits dequantizeLinear ; };
-
input:MLOperand입니다. 입력 텐서입니다. -
scale:MLOperand입니다. zero point로 조정한 후 각 입력 값에 곱할 scale 텐서입니다. 입력과 블록 단위 브로드캐스트 가능해야 합니다. 값은 양수이면서 0이 아니어야 하며, 그렇지 않으면 동작은 구현 정의입니다(예: 올바른 결과, 잘못된 결과 또는 컴파일 실패). -
zeroPoint:MLOperand입니다. 각 입력 값에서 뺄 zero point 텐서입니다. scale과 동일한 shape을 갖습니다. -
options:MLOperatorOptions입니다. 연산의 선택적 매개변수를 지정합니다.
반환: MLOperand입니다.
역양자화된 값을 포함하는 출력 텐서입니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
input
| "uint8",
"int8",
"uint32",
"int32"
| "uint8",
"int8"
| N | 0에서 5까지 |
scale
| "float32",
"float16"
| "float32",
"float16"
| input과
동일한 rank
| 0에서 5까지 |
zeroPoint
| input과
동일한 유형
| "uint8",
"int8",
"int32"
| input과
동일한 rank
| 0에서 5까지 |
| 출력 | scale과
동일한 유형
| "float32",
"float16"
| input과
동일한 rank
| 0에서 5까지 |
MLQuantizeDequantizeLinearSupportLimits에는
다음 멤버가 있습니다.
input, 유형은 MLTensorLimits-
입력 피연산자에 대한
MLTensorLimits입니다. scale, 유형은 MLTensorLimits-
scale 피연산자에 대한
MLTensorLimits입니다. zeroPoint, 유형은 MLTensorLimits-
zeroPoint 피연산자에 대한
MLTensorLimits입니다. output, 유형은 MLTensorLimits-
출력 피연산자에 대한
MLTensorLimits입니다.
MLOpSupportLimits에는
dequantizeLinear()에
대해 다음 멤버가 있습니다.
dequantizeLinear, 유형은 MLQuantizeDequantizeLinearSupportLimits-
dequantizeLinear()연산자의 지원 제한입니다.
dequantizeLinear(input, scale, zeroPoint, options)
메서드의 단계는 다음과 같습니다.
-
this.
[[hasBuilt]]이 true이면 "InvalidStateError"DOMException을 throw합니다. -
this와 input, scale, 그리고 zeroPoint 중 하나를 사용하여 피연산자를 검증한 결과가 false이면
TypeError를 throw합니다. -
input의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름)
TypeError를 throw합니다. -
scale의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름)
TypeError를 throw합니다. -
zeroPoint의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름)
TypeError를 throw합니다. -
zeroPoint의 dataType이 input의 dataType과 같지 않으면
TypeError를 throw합니다. -
scale의 rank 또는 zeroPoint의 rank가 input의 rank와 같지 않으면
TypeError를 throw합니다. -
scale의 shape과 input의 shape을 블록 단위 브로드캐스트한 결과가 false이면
TypeError를 throw합니다. -
zeroPoint의 shape과 input의 shape을 블록 단위 브로드캐스트한 결과가 false이면
TypeError를 throw합니다. -
outputDescriptor를 scale의 dataType과 input의 shape이 주어진 상태에서 MLOperandDescriptor를 생성한 결과로 둡니다.
-
그래프 연결을 구성합니다.
-
output을 this와 outputDescriptor가 주어진 상태에서 MLOperand를 생성한 결과로 둡니다.
-
operator를 input, scale, zeroPoint, 그리고 options가 주어진 "dequantizeLinear" 연산에 대한 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
사용자 에이전트에는 일반적으로 더 효율적인 구현이 있지만, 이 연산의 동작은 다음과 같이 다른 연산을 사용하여 일반적으로 에뮬레이션할 수 있습니다. 기반 플랫폼이 연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로 사용할 수 있습니다.
function dequantizeLinear( builder, input, scale, zeroPoint, options) { // output = (input - zeroPoint) * scale const floatInput= builder. cast( input, scale. dataType); const floatZeroPoint= builder. cast( zeroPoint, scale. dataType); const upsampledScale= blockwiseExpand( builder, scale, input. shape); const upsampledZeroPoint= blockwiseExpand( builder, floatZeroPoint, input. shape); return builder. mul( builder. sub( floatInput, upsampledZeroPoint), upsampledScale); } function blockwiseExpand( builder, input, outputShape) { // 원래 입력과 원하는 출력 shape이 주어지면 각 축을 확장합니다. // 해당 축별 블록을 필요한 횟수만큼 반복합니다. 다만 백엔드 // 구현에는 여러 차원을 받아 모든 차원을 한 번에 // 정수 배수로 업샘플링할 수 있는 훨씬 효율적인 업샘플링 연산자가 있을 수 있습니다. // 최근접 이웃 리샘플링을 사용하는 경우(tile과 유사): // output = resample(scale, {sizes: input.shape}) let output= input; for ( let axis= 0 ; axis< input. shape. length; ++ axis) { const oldShape= output. shape; const oldDimensionLength= oldShape[ axis]; const newDimensionLength= outputShape[ axis]; if ( newDimensionLength!= oldDimensionLength) { // tile/expand는 전체 차원의 반복만 허용하므로 // 슬라이스(축을 따라 개별 요소를 반복하는 것이 아님)를 위해 일시적으로 // 텐서의 shape을 변경하여 요소를 전체 // 블록 크기까지 브로드캐스트할 수 있게 하며, 크기가 1인 차원을 삽입합니다. const elementRepeatCount= newDimensionLength/ oldDimensionLength; const flattenedShape= getFlattenedShapeAroundAxis( oldShape, axis); const unexpandedShape= [ flattenedShape[ 0 ], flattenedShape[ 1 ], 1 , flattenedShape[ 2 ]]; const expandedShape= [ flattenedShape[ 0 ], flattenedShape[ 1 ], elementRepeatCount, flattenedShape[ 2 ] ]; const reshapedInput= builder. reshape( output, unexpandedShape); output= builder. expand( reshapedInput, expandedShape); let newShape= [... oldShape]; newShape[ axis] = newDimensionLength; output= builder. reshape( output, newShape); } } return output; } // 주어진 축의 앞과 뒤에서 평탄화된 shape을 계산하여 // 3개 요소 목록을 생성합니다. 예: // - inputShape = [2,3,4,5,6] with axis = 2 yields shape [6,4,30]. // - inputShape = [4] with axis = 0 yields shape [1,4,1]. function getFlattenedShapeAroundAxis( inputShape, axis) { axis= Math. max( Math. min( axis, inputShape. length- 1 ), 0 ); const shapeBefore= inputShape. slice( 0 , axis); const shapeAfter= inputShape. slice( axis+ 1 , inputShape. length); const countBefore= shapeBefore. reduce(( a, b) => a* b, 1 ); const countAfter= shapeAfter. reduce(( a, b) => a* b, 1 ); return [ countBefore, inputShape[ axis], countAfter]; }
8.9.17. quantizeLinear
scale과 zero-point 바이어스를 사용하여 부동 소수점 텐서를 정수 텐서로 양자화합니다(예: "uint8"의 경우output = clamp(roundEven(input / scale) + zeroPoint, 0, 255)). scale 및
zeroPoint 텐서는 input 텐서보다 작을 수 있으며, 이는 블록 단위 브로드캐스트되기 때문입니다.
partial interface MLGraphBuilder {MLOperand quantizeLinear (MLOperand input ,MLOperand scale ,MLOperand zeroPoint ,optional MLOperatorOptions options = {}); };partial dictionary MLOpSupportLimits {MLQuantizeDequantizeLinearSupportLimits quantizeLinear ; };
-
input:MLOperand입니다. 입력 텐서입니다. -
scale:MLOperand입니다. zero point로 조정하기 전에 각 입력 값을 나눌 scale 텐서입니다. 입력과 블록 단위 브로드캐스트 가능해야 합니다. 값은 양수이면서 0이 아니어야 하며, 그렇지 않으면 동작은 구현에 따라 달라집니다(예: 올바른 결과, 잘못된 결과 또는 컴파일 실패). -
zeroPoint:MLOperand입니다. 재조정된 각 입력 값에 더할 zero point 텐서입니다. scale과 동일한 shape을 갖습니다. -
options:MLOperatorOptions입니다. 연산의 선택적 매개변수를 지정합니다.
반환: MLOperand입니다.
양자화된 값을 포함하는 출력 텐서입니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
input
| "float32",
"float16"
| "float32",
"float16"
| N | 0에서 5까지 |
scale
| input과
동일한 유형
| "float32",
"float16"
| input과
동일한 rank
| 0에서 5까지 |
zeroPoint
| "uint8",
"int8",
"uint32",
"int32"
| "uint8",
"int8"
| input과
동일한 rank
| 0에서 5까지 |
| 출력 | zeroPoint와
동일한 유형
| "uint8",
"int8"
| input과
동일한 rank
| 0에서 5까지 |
MLOpSupportLimits에는
quantizeLinear()에
대해 다음 멤버가 있습니다.
quantizeLinear, 유형은 MLQuantizeDequantizeLinearSupportLimits-
quantizeLinear()연산자의 지원 제한입니다.
quantizeLinear(input, scale, zeroPoint, options)
메서드의 단계는 다음과 같습니다.
-
this.
[[hasBuilt]]이 true이면 "InvalidStateError"DOMException을 throw합니다. -
this와 input, scale, 그리고 zeroPoint 중 하나를 사용하여 피연산자를 검증한 결과가 false이면
TypeError를 throw합니다. -
input의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름)
TypeError를 throw합니다. -
scale의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름)
TypeError를 throw합니다. -
scale의 dataType이 input의 dataType과 같지 않으면
TypeError를 throw합니다. -
zeroPoint의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름)
TypeError를 throw합니다. -
scale의 rank 또는 zeroPoint의 rank가 input의 rank와 같지 않으면
TypeError를 throw합니다. -
scale의 shape과 input의 shape을 블록 단위 브로드캐스트한 결과가 false이면
TypeError를 throw합니다. -
zeroPoint의 shape과 input의 shape을 블록 단위 브로드캐스트한 결과가 false이면
TypeError를 throw합니다. -
outputDescriptor를 zeroPoint의 dataType과 input의 shape이 주어진 상태에서 MLOperandDescriptor를 생성한 결과로 둡니다.
-
그래프 연결을 구성합니다.
-
output을 this와 outputDescriptor가 주어진 상태에서 MLOperand를 생성한 결과로 둡니다.
-
operator를 input, scale, zeroPoint, 그리고 options가 주어진 "quantizeLinear" 연산에 대한 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
사용자 에이전트에는 일반적으로 더 효율적인 구현이 있지만, 이 연산의 동작은 다음과 같이 다른 연산을 사용하여 일반적으로 에뮬레이션할 수 있습니다. 기반 플랫폼이 연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로 사용할 수 있습니다.
function quantizeLinear( builder, input, scale, zeroPoint, options) { // output = clamp(roundEven(input / scale) + zeroPoint, 0, 255) // blockwiseExpand는 dequantizeLinear에 정의되어 있습니다. const floatZeroPoint= builder. cast( zeroPoint, scale. dataType); const upsampledScale= blockwiseExpand( builder, scale, input. shape); const upsampledZeroPoint= blockwiseExpand( builder, floatZeroPoint, input. shape); const quantizedInput= builder. roundEven( builder. div( input, upsampledScale)); const zeroPointAdjustedInput= builder. add( quantizedInput, upsampledZeroPoint); const clampedInput= builder. clamp( zeroPointAdjustedInput, { 'minValue' : 0 , 'maxValue' : 255 }); return builder. cast( clampedInput, zeroPoint. dataType); }
8.9.18. elu
입력 텐서에 대해 요소별로 지수 선형 유닛 함수(ELU)를 계산합니다. 계산은 다음 식을 따릅니다.max(0, x) + alpha * (exp(min(0, x)) - 1).
dictionary :MLEluOptions MLOperatorOptions {double alpha = 1; };partial interface MLGraphBuilder {MLOperand elu (MLOperand input ,optional MLEluOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits elu ; };
MLEluOptions에는
다음 멤버가 있습니다.
alpha, 유형은 double이며 기본값은1-
스칼라 배수입니다.
-
input:MLOperand입니다. 입력 텐서입니다. -
options: 선택적MLEluOptions입니다. 연산의 선택적 매개변수입니다.
반환:
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
input
| "float32",
"float16"
| "float32",
"float16"
| N | 0에서 5까지 |
| 출력 | input과
동일한 유형
| "float32",
"float16"
| input과
동일한 rank
| 0에서 5까지 |
MLOpSupportLimits에는
elu()에
대해 다음 멤버가 있습니다.
elu, 유형은 MLSingleInputSupportLimits-
elu()연산자의 지원 제한입니다.
elu(input, options) 메서드의
단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 "
InvalidStateError"DOMException을 throw합니다. -
this와 input을 사용하여 피연산자를 검증한 결과가 false이면
TypeError를 throw합니다. -
input의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름)
TypeError를 throw합니다. -
options.
alpha를 options.alpha를 input의 dataType으로 캐스트한 결과로 설정합니다. -
그래프 연결을 구성합니다.
-
output을 input이 주어진 상태에서 MLOperand를 복사한 결과로 둡니다.
-
operator를 options가 주어진 "elu" 연산에 대한 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
사용자 에이전트에는 일반적으로 더 효율적인 구현이 있지만, 이 연산의 동작은 다음과 같이 다른 연산을 사용하여 일반적으로 에뮬레이션할 수 있습니다. 기반 플랫폼이 연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로 사용할 수 있습니다.
function elu( builder, input, options) { return builder. add( builder. max( builder. constant( input. dataType, 0 ), input), builder. mul( builder. constant( input. dataType, options. alpha), builder. sub( builder. exp( builder. min( builder. constant( input. dataType, 0 ), input)), builder. constant( input. dataType, 1 )))); }
8.9.19. expand
새 shape에 따라 입력 텐서에서 크기가 1인 임의의 차원을 더 큰 크기로 확장합니다. 이 확장은 [numpy-broadcasting-rule]과 일치합니다. 입력 텐서는 새 shape으로 단방향 브로드캐스트 가능해야 하며, 각 차원의 크기는 1이거나 새 shape에 따른 대응 출력 차원의 크기와 일치해야 합니다.partial interface MLGraphBuilder {MLOperand expand (MLOperand input ,sequence <[EnforceRange ]unsigned long >newShape ,optional MLOperatorOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits expand ; };
-
input:MLOperand입니다. 입력 텐서입니다. -
newShape: sequence<unsigned long>입니다. 입력 텐서를 확장할 새 shape입니다. -
options:MLOperatorOptions입니다. 연산의 선택적 매개변수를 지정합니다.
반환: MLOperand입니다.
크기가 확장된 shape을 가진 텐서입니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
input
| 모든 유형 | "float32",
"float16",
"int32"
| N | 0에서 5까지 |
| 출력 | input과
동일한 유형
| "float32",
"float16",
"int32"
| N | 0에서 5까지 |
MLOpSupportLimits에는
expand()에
대해 다음 멤버가 있습니다.
expand, 유형은 MLSingleInputSupportLimits-
expand()연산자의 지원 제한입니다.
expand(input, newShape, options)
메서드의 단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 "
InvalidStateError"DOMException을 throw합니다. -
this와 input을 사용하여 피연산자를 검증한 결과가 false이면
TypeError를 throw합니다. -
outputShape을 input의 shape과 newShape을 단방향 브로드캐스트한 결과로 둡니다.
-
outputShape의 크기가 출력 텐서의 허용되는 rank가 아니면(이 표에 따름)
TypeError를 throw합니다. -
outputDescriptor를 input의 dataType과 outputShape이 주어진 상태에서 MLOperandDescriptor를 생성한 결과로 둡니다.
-
그래프 연결을 구성합니다.
-
output을 this와 outputDescriptor가 주어진 상태에서 MLOperand를 생성한 결과로 둡니다.
-
operator를 input, newShape, 그리고 options가 주어진 "expand" 연산에 대한 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
8.9.20. gather
인덱스에 따라 축을 따라 입력 텐서의 값을 수집합니다.dictionary :MLGatherOptions MLOperatorOptions { [EnforceRange ]unsigned long axis = 0; };partial interface MLGraphBuilder {MLOperand gather (MLOperand input ,MLOperand indices ,optional MLGatherOptions options = {}); };dictionary {MLGatherSupportLimits MLTensorLimits input ;MLTensorLimits indices ;MLTensorLimits output ; };partial dictionary MLOpSupportLimits {MLGatherSupportLimits gather ; };
MLGatherOptions에는
다음 멤버가 있습니다.
axis, 유형은 unsigned long이며 기본값은0-
수집된 값을 가져올 축입니다. 값은 [0, N-1] 범위여야 하며, 여기서 N은 입력 텐서의 rank입니다.
-
input:MLOperand입니다. 값을 수집할 입력 N차원 텐서입니다. -
indices:MLOperand입니다. 수집할 입력 값의 인덱스 N차원 텐서입니다. 값은"int32","uint32", 또는"int64"유형이어야 하며, -N(포함)부터 N(제외) 범위여야 합니다. 여기서 N은axis로 인덱싱되는 입력 차원의 크기이며, 음수 인덱스는 차원의 끝에서부터 인덱싱함을 의미합니다. -
options: 선택적MLGatherOptions입니다. 연산의 선택적 매개변수입니다.
반환: MLOperand입니다.
rank가 input의
rank
+ indices의
rank
- 1과 같은 출력 N차원 텐서입니다.
indices
매개변수는 gather()에
대해
그래프를 빌드할 때 입력을 실행 전까지 알 수 없으므로 허용 범위로 제한할 수
없습니다. 기반 플랫폼이 지정된 제한 동작을 제공하지 않는 경우 구현은 컴파일된 그래프에 clamp()를
도입할 수 있습니다. 마찬가지로 기반 플랫폼이 음수 인덱스를 지원하지 않는 경우 구현은
컴파일된 그래프에 연산을 도입하여 차원의 끝에서부터의 음수 인덱스를 양수
인덱스로 변환할 수 있습니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
input
| 모든 유형 | "float32",
"float16",
"int32",
"int8",
"uint8"
| 1에서 N까지 | 1에서 5까지 |
indices
| "int32",
"uint32",
"int64"
| "int32"
| N | 0에서 5까지 |
| 출력 | input과
동일한 유형
| "float32",
"float16",
"int32",
"int8",
"uint8"
| N | 0에서 5까지 |
MLGatherSupportLimits에는
다음 멤버가 있습니다.
input, 유형은 MLTensorLimits-
입력 피연산자에 대한
MLTensorLimits입니다. indices, 유형은 MLTensorLimits-
indices 피연산자에 대한
MLTensorLimits입니다. output, 유형은 MLTensorLimits-
출력 피연산자에 대한
MLTensorLimits입니다.
MLOpSupportLimits에는
gather()에
대해 다음 멤버가 있습니다.
gather, 유형은 MLGatherSupportLimits-
gather()연산자의 지원 제한입니다.
gather(input, indices, options)
메서드의 단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 "
InvalidStateError"DOMException을 throw합니다. -
this와 input 및 indices 중 하나를 사용하여 피연산자를 검증한 결과가 false이면
TypeError를 throw합니다. -
indices의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름)
TypeError를 throw합니다. -
indicesShape을 indices의 shape으로 둡니다.
-
axis를 options.
axis로 둡니다. -
dimCount를 0으로 둡니다.
-
outputRank를 0으로 둡니다.
-
outputShape을 빈 목록으로 둡니다.
-
inputShape의 각 size에 대해 각각:
-
dimCount가 axis와 같으면 중단합니다.
-
outputShape[dimCount]를 size로 설정합니다.
-
dimCount를 1 증가시킵니다.
-
-
outputRank를 dimCount로 설정합니다.
-
dimCount를 0으로 둡니다.
-
indicesShape의 각 size에 대해 각각:
-
outputShape[outputRank + dimCount]를 size로 설정합니다.
-
dimCount를 1 증가시킵니다.
-
-
outputRank를 outputRank + dimCount로 설정합니다.
-
dimCount를 0으로 둡니다.
-
inputShape의 각 size에 대해 각각:
-
dimCount가 axis보다 작거나 같으면 계속합니다.
-
outputShape[outputRank + dimCount - axis - 1]을 size로 설정합니다.
-
dimCount를 1 증가시킵니다.
-
-
desc를 input의 dataType과 outputShape이 주어진 상태에서 MLOperandDescriptor를 생성한 결과로 둡니다.
-
그래프 연결을 구성합니다.
-
output을 desc가 주어진 상태에서 MLOperand를 생성한 결과로 둡니다.
-
operator를 input, indices, 그리고 options가 주어진 "gather" 연산에 대한 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input과 indices로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
다양한 슬라이싱 방식에서 gather가 작동하는 방식의 예입니다.
// shape이 [4,3]인 input: // [[ 0, 1, 2], // [10, 11, 12], // [20, 21, 22], // [30, 31, 32]] // axis = 0 (기본값) // shape이 [2]인 indices: // [3,1] // shape이 [2,3]인 output: // [[30, 31, 32], // [10, 11, 12]] const indices1= builder. constant({ dataType: 'uint32' , shape: [ 2 ]}, new Uint32Array([ 3 , 1 ])); const output1= builder. gather( input, indices1); // axis = 1 // shape이 [3]인 indices: // [2,1,1] // shape이 [4,3]인 output: // [[ 2, 1, 1], // [12, 11, 11], // [22, 21, 21], // [32, 31, 31]] const indices2= builder. constant( { dataType: 'uint32' , shape: [ 3 ]}, new Uint32Array([ 2 , 1 , 1 ])); const output2= builder. gather( input, indices2, { axis: 1 }); // axis = 1 // shape이 [2,2]인 indices: // [[0, 1], // [1, 2]] // shape이 [4,2,2]인 output: // [[[ 0, 1], [ 1, 2]], // [[10, 11], [11, 12]], // [[20, 21], [21, 22]], // [[30, 31], [31, 32]]] const indices3= builder. constant( { dataType: 'uint32' , shape: [ 2 , 2 ]}, new Uint32Array([ 0 , 1 , 1 , 2 ])); const output3= builder. gather( input, indices3, { axis: 1 });
8.9.21. gatherElements
인덱스에 따라 축을 따라 입력 텐서의 값을 수집합니다.partial interface MLGraphBuilder {MLOperand gatherElements (MLOperand input ,MLOperand indices ,optional MLGatherOptions options = {}); };partial dictionary MLOpSupportLimits {MLGatherSupportLimits gatherElements ; };
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
input
| 모든 유형 | "float32",
"float16",
"int32"
| 1에서 N까지 | 1에서 5까지 |
indices
| "int32",
"uint32",
"int64"
| "int32"
| input과
동일한 rank
| 1에서 5까지 |
| 출력 | input과
동일한 유형
| "float32",
"float16",
"int32"
| input과
동일한 rank
| 1에서 5까지 |
MLOpSupportLimits에는
gatherElements()에
대해 다음 멤버가 있습니다.
gatherElements, 유형은 MLGatherSupportLimits-
gatherElements()연산자의 지원 제한입니다.
indices
매개변수는 gatherElements()에
대해
그래프를 빌드할 때 입력을 실행 전까지 알 수 없으므로 허용 범위로 제한할 수
없습니다. 기반 플랫폼이 지정된 제한 동작을 제공하지 않는 경우 구현은 컴파일된 그래프에 clamp()를
도입할 수 있습니다. 마찬가지로 기반 플랫폼이 음수 인덱스를 지원하지 않는 경우 구현은
컴파일된 그래프에 연산을 도입하여 차원의 끝에서부터의 음수 인덱스를 양수
인덱스로 변환할 수 있습니다.
gatherElements(input, indices, options)
메서드의 단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 "
InvalidStateError"DOMException을 throw합니다. -
this와 input 및 indices 중 하나를 사용하여 피연산자를 검증한 결과가 false이면
TypeError를 throw합니다. -
indices의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름)
TypeError를 throw합니다. -
input 또는 indices 중 하나의 rank가 해당 허용되는 rank가 아니면
TypeError를 throw합니다. -
axis를 options.
axis로 둡니다. -
indicesShapeExpected를 input의 shape의 복사본으로 둡니다.
-
indicesShapeExpected[axis]를 indices의 shape[axis]로 설정합니다.
-
indices의 shape이 indicesShapeExpected와 같지 않으면
TypeError를 throw합니다. -
그래프 연결을 구성합니다.
-
output을 input이 주어진 상태에서 MLOperand를 복사한 결과로 둡니다.
-
operator를 input, indices, 그리고 options가 주어진 "gatherElements" 연산에 대한 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input과 indices로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
다양한 슬라이싱 방식에서 gatherElements가 작동하는 방식의 예입니다.
// shape이 [4,3]인 input: // [[ 0, 1, 2], // [10, 11, 12], // [20, 21, 22], // [30, 31, 32]] // shape이 [2,3]인 indices: // [[3, 1, 1], // [2, 0, 3]] // axis = 0 (기본값) // shape이 [2,3]인 output: // [[30, 11, 12], // [20, 1, 32]] const input1= builder. constant( { dataType: 'float32' , shape: [ 4 , 3 ]}, new Float32Array([ 0 , 1 , 2 , 10 , 11 , 12 , 20 , 21 , 22 , 30 , 31 , 32 ])); const indices1= builder. constant( { dataType: 'uint32' , shape: [ 2 , 3 ]}, new Uint32Array([ 3 , 1 , 1 , 2 , 0 , 3 ])); const output1= builder. gatherElements( input1, indices1); // shape이 [4,3]인 input: // [[ 0, 1, 2], // [10, 11, 12], // [20, 21, 22], // [30, 31, 32]] // shape이 [4,1]인 indices: // [[2], // [1], // [0], // [2]], // axis = 1 // shape이 [4,1]인 output: // [[ 2], // [11], // [20], // [32]] const indices2= builder. constant( { dataType: 'uint32' , shape: [ 4 , 1 ]}, new Uint32Array([ 2 , 1 , 0 , 2 ])); const output2= builder. gatherElements( input1, indices2, { axis: 1 }); // shape이 [4,2,2]인 input: // [[[ 0, 1], // [ 10, 11]], // [[100, 101], // [110, 111]], // [[200, 201], // [210, 211]], // [[300, 301], // [310, 311]],] // shape이 [1,2,2]인 indices: // [[[0, 2], // [1, 3]]], // axis = 0 // shape이 [1,2,2]인 output: // [[[ 0, 201], // [110, 311]]] const inputData3= new Float32Array( [ 0 , 1 , 10 , 11 , 100 , 101 , 110 , 111 , 200 , 201 , 210 , 211 , 300 , 301 , 310 , 311 ]); const input3= builder. constant({ dataType: 'float32' , shape: [ 4 , 2 , 2 ]}, inputData3); const indices3= builder. constant( { dataType: 'uint32' , shape: [ 1 , 2 , 2 ]}, new Uint32Array([ 0 , 2 , 1 , 3 ])); const output3= builder. gatherElements( input3, indices3, { axis: 0 });
8.9.22. gatherND
인덱스에 따라 입력 텐서의 슬라이스를 수집합니다.partial interface MLGraphBuilder {MLOperand gatherND (MLOperand input ,MLOperand indices ,optional MLOperatorOptions options = {}); };partial dictionary MLOpSupportLimits {MLGatherSupportLimits gatherND ; };
-
input:MLOperand입니다. 값을 수집할 입력 N차원 텐서입니다. -
indices:MLOperand입니다. indices 배열에는 입력 텐서에 대한 전체 좌표가 포함되며, 가장 오른쪽 차원에는 좌표당 차원 수가 들어 있습니다. 따라서 shape이 [10,1]인 indices 텐서는 10개의 단일 축 인덱스를 포함하고, shape이 [4,3]이면 3차원 좌표의 인덱스 4개를 포함합니다. 값은"int32","uint32", 또는"int64"유형이어야 하며, 각각 -N(포함)부터 N(제외) 범위여야 합니다. 여기서 N은 대응하는 입력 차원의 크기이며, 음수 인덱스는 대응하는 차원의 끝에서부터 인덱싱함을 의미합니다. -
options: 선택적MLOperatorOptions입니다. 연산의 선택적 매개변수입니다.
반환: MLOperand입니다.
rank가 input의
rank + indices의
rank - indices의
shape[-1] - 1과 같은 출력
N차원 텐서입니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
input
| 모든 유형 | "float32",
"float16",
"int32",
"int8",
"uint8"
| 1에서 N까지 | 1에서 5까지 |
indices
| "int32",
"uint32",
"int64"
| "int32"
| 1에서 N까지 | 1에서 5까지 |
| 출력 | input과
동일한 유형
| "float32",
"float16",
"int32",
"int8",
"uint8"
| N | 0에서 5까지 |
MLOpSupportLimits에는
gatherND()에
대해 다음 멤버가 있습니다.
gatherND, 유형은 MLGatherSupportLimits-
gatherND()연산자의 지원 제한입니다.
indices
매개변수는 gatherND()에
대해
그래프를 빌드할 때 입력을 실행 전까지 알 수 없으므로 허용 범위로 제한할 수
없습니다. 기반 플랫폼이 지정된 제한 동작을 제공하지 않는 경우 구현은 컴파일된 그래프에 clamp()를
도입할 수 있습니다. 마찬가지로 기반 플랫폼이 음수 인덱스를 지원하지 않는 경우 구현은
컴파일된 그래프에 연산을 도입하여 차원의 끝에서부터의 음수 인덱스를 양수
인덱스로 변환할 수 있습니다.
gatherND(input, indices, options)
메서드의 단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 "
InvalidStateError"DOMException을 throw합니다. -
this와 input 및 indices 중 하나를 사용하여 피연산자를 검증한 결과가 false이면
TypeError를 throw합니다. -
indices의 dataType이 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름)
TypeError를 throw합니다. -
input 또는 indices 중 하나의 rank가 해당 허용되는 rank가 아니면
TypeError를 throw합니다. -
indicesShape을 indices의 shape으로, indicesRank를 indices의 rank로 둡니다.
-
input 또는 indices 중 하나의 rank가 해당 허용되는 rank가 아니면
TypeError를 throw합니다. -
indexableSize를 indicesRank - 1로 둡니다.
-
coordinateSize를 indicesShape[indexableSize]로 둡니다.
-
outputShape을 빈 목록으로 둡니다.
-
0부터 indexableSize까지의 범위에서 각 index에 대해 각각(상한 제외):
-
indicesShape[index]를 outputShape에 추가합니다.
-
-
coordinateSize부터 inputRank까지의 범위에서 각 index에 대해 각각(상한 제외):
-
inputShape[index]를 outputShape에 추가합니다.
-
-
outputDesc를 input의 dataType과 outputShape이 주어진 상태에서 MLOperandDescriptor를 생성한 결과로 둡니다.
-
그래프 연결을 구성합니다.
-
output을 outputDesc가 주어진 상태에서 MLOperand를 생성한 결과로 둡니다.
-
operator를 input, indices, 그리고 options가 주어진 "gatherND" 연산에 대한 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input과 indices로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
다양한 슬라이싱 방식에서 gatherND가 작동하는 방식의 예입니다.
// shape이 [2,2]인 input: // [[0, 1], // [2, 3]] // shape이 [3,2]인 indices: // [[0, 0], // [1, 1], // [1, 0]] // shape이 [3]인 output: // [0, 3, 2] const input1= builder. constant( { dataType: 'float32' , shape: [ 2 , 2 ]}, new Float32Array([ 0 , 1 , 2 , 3 ])); const indices1= builder. constant( { dataType: 'uint32' , shape: [ 3 , 2 ]}, new Uint32Array([ 0 , 0 , 1 , 1 , 1 , 0 ])); const output1= builder. gatherND( input1, indices1); // shape이 [2,2]인 input: // [[0, 1], // [2, 3]] // shape이 [2,1]인 indices: // [[1], // [0]] // shape이 [2,2]인 output: // [[2, 3] <= input 좌표 [1, *]의 행 [2, 3] // [0, 1]] <= input 좌표 [0, *]의 행 [0, 1] const indices2= builder. constant( { dataType: 'uint32' , shape: [ 2 , 1 ]}, new Uint32Array([ 1 , 0 ])); const output2= builder. gatherND( input1, indices2); // shape이 [2,2,2]인 input: // [[[0, 1], // [2, 3]], // [[4, 5], // [6, 7]]] // shape이 [2,2]인 indices: // [[0, 1], // [1, 0]] // shape이 [2,2]인 output: // [[2, 3], <= input 좌표 [0, 1, *]의 행 [2, 3] // [4, 5]] <= input 좌표 [1, 0, *]의 행 [4, 5] const input2= builder. constant( { dataType: 'float32' , shape: [ 2 , 2 , 2 ]}, new Float32Array([ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 ])); const indices3= builder. constant( { dataType: 'uint32' , shape: [ 2 , 2 ]}, new Uint32Array([ 0 , 1 , 1 , 0 ])); const output3= builder. gatherND( input2, indices3); // shape이 [2,2,2]인 input: // [[[0, 1], // [2, 3]], // [[4, 5], // [6, 7]]] // shape이 [3,1]인 indices: // [[1], // [0], // [1]] // shape이 [3,2,2]인 output: // [[[4, 5], <= input 좌표 [1, *, *]의 블록 [[4, 5], [6, 7]] // [6, 7]], // [[0, 1], <= input 좌표 [0, *, *]의 블록 [[0, 1], [2, 3]] // [2, 3]], // [[4, 5], <= input 좌표 [1, *, *]의 블록 [[4, 5], [6, 7]] // [6, 7]]] const indices4= builder. constant( { dataType: 'uint32' , shape: [ 3 , 1 ]}, new Uint32Array([ 1 , 0 , 1 ])); const output4= builder. gatherND( input2, indices4); // shape이 [2,2,2]인 input: // [[[0, 1], // [2, 3]], // [[4, 5], // [6, 7]]] // shape이 [5,3]인 indices: // [[0,0,1], // [0,1,0], // [1,0,0], // [1,1,0], // [1,1,1]] // shape이 [5]인 output: // [1,2,4,6,7] const indices5= builder. constant( { dataType: 'uint32' , shape: [ 5 , 3 ]}, new Uint32Array([ 0 , 0 , 1 , 0 , 1 , 0 , 1 , 0 , 0 , 1 , 1 , 0 , 1 , 1 , 1 ])); const output5= builder. gatherND( input2, indices5);
8.9.23. gelu
입력 텐서의 가우시안 오류 선형 유닛 함수(GELU)를 계산합니다. 계산은 다음 식을 따릅니다.0.5 * x * (1 + erf(x / sqrt(2))).
partial interface MLGraphBuilder {MLOperand gelu (MLOperand input ,optional MLOperatorOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits gelu ; };
-
input:MLOperand입니다. 입력 텐서입니다. -
options:MLOperatorOptions입니다. 연산의 선택적 매개변수를 지정합니다.
반환:
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
input
| "float32",
"float16"
| "float32",
"float16"
| N | 0에서 5까지 |
| 출력 | input과
동일한 유형
| "float32",
"float16"
| input과
동일한 rank
| 0에서 5까지 |
MLOpSupportLimits에는
gelu()에
대해 다음 멤버가 있습니다.
gelu, 유형은 MLSingleInputSupportLimits-
gelu()연산자의 지원 제한입니다.
gelu(input, options) 메서드의
단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 "
InvalidStateError"DOMException을 throw합니다. -
this와 input을 사용하여 피연산자를 검증한 결과가 false이면
TypeError를 throw합니다. -
input의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름)
TypeError를 throw합니다. -
그래프 연결을 구성합니다.
-
output을 input이 주어진 상태에서 MLOperand를 복사한 결과로 둡니다.
-
operator를 options가 주어진 "gelu" 연산에 대한 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
사용자 에이전트에는 일반적으로 더 효율적인 구현이 있지만, 이 연산의 동작은 다음과 같이 다른 연산을 사용하여 일반적으로 에뮬레이션할 수 있습니다. 기반 플랫폼이 연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로 사용할 수 있습니다.
function gelu( builder, input) { return builder. mul( builder. mul( input, builder. constant( input. dataType, 0.5 )), builder. add( builder. constant( input. dataType, 1 ), builder. erf( builder. div( input, builder. sqrt( builder. constant( input. dataType, 2 )))))); }
8.9.24. gemm
Basic Linear Algebra Subprograms의 일반 행렬 곱셈을 계산합니다. 계산은 다음 식을 따릅니다.alpha * A * B + beta * C. 여기서 A는 shape이 [M, K] 또는
[K, M]인 2차원 텐서이고, B는 shape이 [K, N] 또는 [N, K]인 2차원 텐서이며,
C는 shape [M,
N]으로 단방향 브로드캐스트 가능합니다. A와 B는 계산 전에
선택적으로 전치할 수 있습니다.
dictionary :MLGemmOptions MLOperatorOptions {MLOperand c ;double alpha = 1.0;double beta = 1.0;boolean aTranspose =false ;boolean bTranspose =false ; };partial interface MLGraphBuilder {MLOperand gemm (MLOperand a ,MLOperand b ,optional MLGemmOptions options = {}); };dictionary {MLGemmSupportLimits MLTensorLimits a ;MLTensorLimits b ;MLTensorLimits c ;MLTensorLimits output ; };partial dictionary MLOpSupportLimits {MLGemmSupportLimits gemm ; };
MLGemmOptions에는
다음 멤버가 있습니다.
c, 유형은 MLOperand-
세 번째 입력 텐서입니다. 스칼라이거나 shape [M, N]으로 단방향 브로드캐스트 가능한 shape입니다. 지정되지 않으면
c가 스칼라 0.0인 것처럼 계산합니다. alpha, 유형은 double이며 기본값은1.0-
첫 번째 입력에 대한 배수입니다.
beta, 유형은 double이며 기본값은1.0-
세 번째 입력
c에 대한 배수입니다. aTranspose, 유형은 boolean이며 기본값은false-
출력을 계산하기 전에 첫 번째 입력을 전치할지 나타냅니다.
bTranspose, 유형은 boolean이며 기본값은false-
출력을 계산하기 전에 두 번째 입력을 전치할지 나타냅니다.
-
a:MLOperand입니다.aTranspose가 false이면 shape이 [M, K]인 첫 번째 입력 2차원 텐서이고,aTranspose가 true이면 [K, M]입니다. -
b:MLOperand입니다.bTranspose가 false이면 shape이 [K, N]인 두 번째 입력 2차원 텐서이고,bTranspose가 true이면 [N, K]입니다. -
options: 선택적MLGemmOptions입니다. 연산의 선택적 매개변수입니다.
반환: MLOperand입니다.
모든 입력의 계산된 곱을 포함하는 shape [M, N]의 출력 2차원 텐서입니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
a
| "float32",
"float16"
| "float32",
"float16"
| 2 | 2 |
b
| a와
동일한 유형
| "float32",
"float16"
| 2 | 2 |
c
| a와
동일한 유형
| "float32",
"float16"
| 0에서 2까지 | 0에서 2까지 |
| 출력 | a와
동일한 유형
| "float32",
"float16"
| 2 | 2 |
MLGemmSupportLimits에는
다음 멤버가 있습니다.
a, 유형은 MLTensorLimits-
a 피연산자에 대한
MLTensorLimits입니다. b, 유형은 MLTensorLimits-
b 피연산자에 대한
MLTensorLimits입니다. c, 유형은 MLTensorLimits-
c 피연산자에 대한
MLTensorLimits입니다. output, 유형은 MLTensorLimits-
출력 피연산자에 대한
MLTensorLimits입니다.
MLOpSupportLimits에는
gemm()에
대해 다음 멤버가 있습니다.
gemm, 유형은 MLGemmSupportLimits-
gemm()연산자의 지원 제한입니다.
gemm(a, b, options)
메서드의 단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 "
InvalidStateError"DOMException을 throw합니다. -
this와 a 및 b 중 하나를 사용하여 피연산자를 검증한 결과가 false이면
TypeError를 throw합니다. -
a 또는 b 중 하나의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름)
TypeError를 throw합니다. -
options.
alpha를 options.alpha를 a의 dataType으로 캐스트한 결과로 설정합니다. -
options.
aTranspose가 true이면 shapeA의 항목 순서를 뒤집습니다. -
options.
bTranspose가 true이면 shapeB의 항목 순서를 뒤집습니다. -
-
shape « shapeA[0], shapeB[1] »로 단방향 브로드캐스트 가능하지 않으면
TypeError를 throw합니다. -
그 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름)
TypeError를 throw합니다.
-
-
desc를 a의 dataType과 « shapeA[0], shapeB[1] »이 주어진 상태에서 MLOperandDescriptor를 생성한 결과로 둡니다.
-
그래프 연결을 구성합니다.
-
output을 this와 desc가 주어진 상태에서 MLOperand를 생성한 결과로 둡니다.
-
operator를 options가 주어진 "gemm" 연산에 대한 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 a와 b로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
사용자 에이전트에는 일반적으로 더 효율적인 구현이 있지만, 이 연산의 동작은 다음과 같이 다른 연산을 사용하여 일반적으로 에뮬레이션할 수 있습니다. 기반 플랫폼이 연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로 사용할 수 있습니다.
function gemm( builder, a, b, options) { if ( options. aTranspose) a= builder. transpose( a); if ( options. bTranspose) b= builder. transpose( b); let ab= builder. matmul( builder. mul( builder. constant( a. dataType, options. alpha), a), b); return ( options. c? builder. add( ab, builder. mul( builder. constant( a. dataType, options. beta), options. c)) : ab); }
8.9.25. gru
Gated Recurrent Unit [GRU] 순환 네트워크는 update, reset 및 new gate를 사용하여 네트워크의 시간적 시퀀스를 따라 출력으로 전달되는 출력 상태를 계산합니다.enum {MLGruWeightLayout , // update-reset-new gate 순서"zrn" // reset-update-new gate 순서 };"rzn" enum {MLRecurrentNetworkActivation ,"relu" ,"sigmoid" };"tanh" enum {MLRecurrentNetworkDirection ,"forward" ,"backward" };"both" dictionary :MLGruOptions MLOperatorOptions {MLOperand bias ;MLOperand recurrentBias ;MLOperand initialHiddenState ;boolean resetAfter =true ;boolean returnSequence =false ;MLRecurrentNetworkDirection direction = "forward";MLGruWeightLayout layout = "zrn";sequence <MLRecurrentNetworkActivation >activations ; };partial interface MLGraphBuilder {sequence <MLOperand >gru (MLOperand input ,MLOperand weight ,MLOperand recurrentWeight , [EnforceRange ]unsigned long steps , [EnforceRange ]unsigned long hiddenSize ,optional MLGruOptions options = {}); };dictionary {MLGruSupportLimits MLTensorLimits input ;MLTensorLimits weight ;MLTensorLimits recurrentWeight ;MLTensorLimits bias ;MLTensorLimits recurrentBias ;MLTensorLimits initialHiddenState ;MLTensorLimits output0 ;MLTensorLimits output1 ; };partial dictionary MLOpSupportLimits {MLGruSupportLimits gru ; };
MLGruOptions
에는 다음 멤버가 있습니다.
bias, 유형은 MLOperand-
shape이 [numDirections, 3 * hiddenSize]인 2차원 입력 bias 텐서입니다. 텐서 shape의 두 번째 차원에서 bias 벡터의 순서는
layout에 따라 지정됩니다. recurrentBias, 유형은 MLOperand-
shape이 [numDirections, 3 * hiddenSize]인 2차원 recurrent bias 텐서입니다. 텐서 shape의 두 번째 차원에서 bias 벡터의 순서는
layout에 따라 지정됩니다. initialHiddenState, 유형은 MLOperand-
shape이 [numDirections, batchSize, hiddenSize]인 3차원 초기 hidden state 텐서입니다. 지정되지 않은 경우 구현은 반드시 0으로 채운 텐서를 사용해야 합니다.
resetAfter, 유형은 boolean이며 기본값은true-
행렬 곱셈 후 또는 전에 reset gate를 적용할지를 나타냅니다.
returnSequence, 유형은 boolean이며 기본값은false-
마지막 time step의 출력과 더불어 각 time step의 모든 출력을 포함하는 전체 시퀀스도 반환할지를 나타냅니다.
direction, 유형은 MLRecurrentNetworkDirection이며 기본값은"forward"-
입력 시퀀스의 처리 방향입니다.
"both"로 설정하면 weight 및 bias 텐서 shape의 첫 번째 차원 크기는 반드시 2여야 하며, 입력은 양방향으로 처리됩니다. layout, 유형은 MLGruWeightLayout이며 기본값은"zrn"-
GRU의 내부 gate에 대한 weight 및 bias 벡터의 순서로, 구체적으로
update (z),reset (r), 그리고new (n)gate이며, 이는 weight 및 bias 텐서 shape의 두 번째 차원에 표시됩니다. activations, 유형은 sequence<MLRecurrentNetworkActivation>-
첫 번째 함수는 update 및 reset gate에 사용되고 두 번째 함수는 new gate에 사용되는 한 쌍의 활성화 함수를 지정합니다. 지정되지 않은 경우 각각
"sigmoid"및"tanh"함수가 기본값입니다.
-
input:MLOperand입니다. shape이 [steps, batchSize, inputSize]인 입력 3차원 텐서입니다. -
weight:MLOperand입니다. shape이 [numDirections, 3 * hiddenSize, inputSize]인 3차원 입력 weight 텐서입니다. 텐서 shape의 두 번째 차원에서 weight 벡터의 순서는layout에 따라 지정됩니다. -
recurrentWeight:MLOperand입니다. shape이 [numDirections, 3 * hiddenSize, hiddenSize]인 3차원 recurrent weight 텐서입니다. 텐서 shape의 두 번째 차원에서 weight 벡터의 순서는layout에 따라 지정됩니다. -
steps:unsigned long스칼라입니다. 순환 네트워크의 time step 수입니다. 값은 0보다 커야 합니다. -
hiddenSize:unsigned long스칼라입니다. cell 출력 텐서 shape의 세 번째 차원 값입니다. hidden state의 feature 수를 나타냅니다. -
options: 선택적MLGruOptions입니다. 연산의 선택적 매개변수입니다.
반환: sequence<MLOperand>.
첫 번째 요소는 shape이 [numDirections, batchSize, hiddenSize]인 3차원 텐서이며, 네트워크의
마지막 time step에서의 cell 출력입니다. 또한 returnSequence
가 true로 설정된 경우 두 번째 요소는 shape이 [steps, numDirections,
batchSize, hiddenSize]인 4차원 출력 텐서이며 시간적
시퀀스의 각 time step에서 나온 모든 cell 출력을 포함합니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
| "float32",
"float16"
| "float32",
"float16"
| 3 | 3 |
| 동일한 유형
| "float32",
"float16"
| 3 | 3 |
| 동일한 유형
| "float32",
"float16"
| 3 | 3 |
bias
| 동일한 유형
| "float32",
"float16"
| 2 | 2 |
recurrentBias
| 동일한 유형
| "float32",
"float16"
| 2 | 2 |
| 동일한 유형
| "float32",
"float16"
| 3 | 3 |
| outputs[0] | 동일한 유형
| "float32",
"float16"
| 3 | 3 |
outputs[1] if returnSequence
가 true인 경우
| 동일한 유형
| "float32",
"float16"
| 4 | 4 |
MLGruSupportLimits
에는 다음 멤버가 있습니다.
input, 유형은 MLTensorLimits-
입력 피연산자에 대한
MLTensorLimits입니다. weight, 유형은 MLTensorLimits-
weight 피연산자에 대한
MLTensorLimits입니다. recurrentWeight, 유형은 MLTensorLimits-
recurrentWeight 피연산자에 대한
MLTensorLimits입니다. bias, 유형은 MLTensorLimits-
bias 피연산자에 대한
MLTensorLimits입니다. recurrentBias, 유형은 MLTensorLimits-
recurrentBias 피연산자에 대한
MLTensorLimits입니다. initialHiddenState, 유형은 MLTensorLimits-
initialHiddenState 피연산자에 대한
MLTensorLimits입니다. output0, 유형은 MLTensorLimits-
모든 출력 피연산자[0]에 대한
MLTensorLimits입니다. output1, 유형은 MLTensorLimits-
모든 출력 피연산자[1]에 대한
MLTensorLimits입니다.
MLOpSupportLimits
에는 gru()에
대해 다음 멤버가 있습니다.
gru, 유형은 MLGruSupportLimits-
gru()연산자의 지원 제한입니다.
gru(input, weight, recurrentWeight, steps, hiddenSize, options)
메서드의 단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input, weight, recurrentWeight, options.
bias(존재하는 경우), options.recurrentBias(존재하는 경우), 그리고 options.(존재하는 경우) 중 하나가 false를 반환하면 예외를 발생시킵니다.TypeError입니다. -
input, weight 또는 recurrentWeight 중 하나의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름) 예외를 발생시킵니다.
TypeError입니다. -
input, weight 또는 recurrentWeight 중 하나의 rank가 해당 허용되는 rank가 아니면 예외를 발생시킵니다.
TypeError입니다. -
batchSize를 input의 shape[1]로 둡니다.
-
inputSize를 input의 shape[2]로 둡니다.
-
numDirections를 options.
direction이"both"이면 2로, 그렇지 않으면 1로 둡니다. -
weight의 shape이 « numDirections, 3 * hiddenSize, inputSize »와 같지 않으면 예외를 발생시킵니다.
TypeError입니다. -
recurrentWeight의 shape이 « numDirections, 3 * hiddenSize, hiddenSize »와 같지 않으면 예외를 발생시킵니다.
TypeError입니다. -
hiddenSize * 6이 유효한 차원이 아니면 예외를 발생시킵니다.
TypeError입니다.왜 hiddenSize * 6인가요?
일부 기반 플랫폼은bias와recurrentBias를 연결한 단일 bias 텐서에서 동작합니다. 따라서 3 * hiddenSize + 3 * hiddenSize 역시 유효한 차원이어야 합니다. -
options.
recurrentBias가 존재하면: -
options.
가 존재하면: -
options.
activations가 존재하면:-
activations를 options.
activations의 복제본으로 둡니다.
-
그렇지 않으면:
-
출력 shape을 계산합니다.
-
desc0을 input의 dataType과 « numDirections, batchSize, hiddenSize »가 주어진 상태에서 MLOperandDescriptor를 생성한 결과로 둡니다.
-
options.
returnSequence가 true이면:-
desc1을 input의 dataType 과 « steps, numDirections, batchSize, hiddenSize »가 주어진 상태에서 MLOperandDescriptor를 생성한 결과로 둡니다.
-
-
-
그래프 연결을 구성합니다.
-
operator를 weight, recurrentWeight, steps, hiddenSize 및 options가 주어진 "gru" 연산에 대한 연산자로 둡니다.
-
output0을 this와 desc0가 주어진 상태에서 MLOperand를 생성한 결과로 둡니다.
-
options.
returnSequence가 true이면:-
output1을 this 와 desc1이 주어진 상태에서 MLOperand를 생성한 결과로 둡니다.
-
output을 목록 « output0, output1 »로 둡니다.
-
output0.
[[operator]]및 output1.[[operator]]를 operator로 설정합니다.
-
-
그렇지 않으면:
-
output을 목록 « output0 »로 둡니다.
-
output0.
[[operator]]를 operator로 설정합니다.
-
-
operator의 입력을 input, weight, 그리고 recurrentWeight로 설정합니다.
-
options.
recurrentBias가 존재하면 이를 operator의 입력에 추가합니다. -
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
squeeze() 헬퍼를 사용하면, 사용자 에이전트에는 일반적으로 더 효율적인 구현이 있지만 이 연산의 동작을 다음과 같이 다른 연산을 사용하여 일반적으로 에뮬레이션할 수 있습니다. 기반 플랫폼이 연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로 사용할 수 있습니다.
function gru( builder, input, weight, recurrentWeight, steps, hiddenSize, options) { const batchSize= input. shape[ 1 ]; const inputSize= input. shape[ 2 ]; const direction= options. direction|| 'forward' ; const numDirections= ( direction== 'both' ? 2 : 1 ); let hiddenState= options. initialHiddenState; if ( ! hiddenState) { const desc= { dataType: 'float32' , shape: [ numDirections, batchSize, hiddenSize] }; const totalSize= numDirections* batchSize* hiddenSize; hiddenState= builder. constant( desc, new Float32Array( totalSize). fill( 0 )); } let currentWeight= []; let currentRecurrentWeight= []; let currentBias= []; let currentRecurrentBias= []; let forwardSequence= null ; let backwardSequence= null ; let outputHidden= null ; for ( let dir= 0 ; dir< numDirections; ++ dir) { currentWeight. push( squeeze( builder, builder. slice( weight, [ dir, 0 , 0 ], [ 1 , 3 * hiddenSize, inputSize]))); currentRecurrentWeight. push( squeeze( builder, builder. slice( recurrentWeight, [ dir, 0 , 0 ], [ 1 , 3 * hiddenSize, hiddenSize]))); currentBias. push( options. bias? ( squeeze( builder, builder. slice( options. bias, [ dir, 0 ], [ 1 , 3 * hiddenSize]))) : null ); currentRecurrentBias. push( options. recurrentBias? ( squeeze( builder, builder. slice( options. recurrentBias, [ dir, 0 ], [ 1 , 3 * hiddenSize]))) : null ); let currentHidden= squeeze( builder, builder. slice( hiddenState, [ dir, 0 , 0 ], [ 1 , batchSize, hiddenSize]), [ 0 ]); for ( let step= 0 ; step< steps; ++ step) { const slice= ( dir== 1 || direction== 'backward' ? steps- step- 1 : step); const currentInput= squeeze( builder, builder. slice( input, [ slice, 0 , 0 ], [ 1 , batchSize, inputSize]), [ 0 ]); currentHidden= builder. gruCell( currentInput, currentWeight[ dir], currentRecurrentWeight[ dir], currentHidden, hiddenSize, { bias: currentBias[ dir], recurrentBias: currentRecurrentBias[ dir], resetAfter: options. resetAfter, layout: options. layout, activations: options. activations}); if ( options. returnSequence) { // 2차원([batchSize, hiddenSize])인 currentHidden을 확장합니다. // 4차원([steps, numDirections, batchSize, hiddenSize])으로 const expandedHiddenAs4D= builder. reshape( currentHidden, [ 1 , 1 , batchSize, hiddenSize]); if ( direction== 'forward' || ( dir== 0 && direction== 'both' )) { forwardSequence= forwardSequence? builder. concat([ forwardSequence, expandedHiddenAs4D], 0 ) : expandedHiddenAs4D; } else if ( direction== 'backward' || ( dir== 1 && direction== 'both' )) { backwardSequence= backwardSequence? builder. concat([ expandedHiddenAs4D, backwardSequence], 0 ) : expandedHiddenAs4D; } } } // 2차원([batchSize, hiddenSize])인 currentHidden을 확장합니다. // 3차원([numDirections, batchSize, hiddenSize])으로 const expandedHiddenAs3D= builder. reshape( currentHidden, [ 1 , batchSize, hiddenSize]); outputHidden= outputHidden? builder. concat([ outputHidden, expandedHiddenAs3D], 0 ) : expandedHiddenAs3D; } if ( options. returnSequence) { let outputSequence= null ; if ( direction== 'forward' ) { outputSequence= forwardSequence; } else if ( direction== 'backward' ) { outputSequence= backwardSequence; } else if ( direction== 'both' ) { // 축 1을 따라 연결합니다(numDirections 차원). outputSequence= builder. concat([ forwardSequence, backwardSequence], 1 ); } return [ outputHidden, outputSequence]; } else { return [ outputHidden]; } }
8.9.26. gruCell
Gated Recurrent Unit [GRU] 순환 네트워크의 단일 time step으로, update gate와 reset gate를 사용하여 순환 네트워크의 시간적 시퀀스를 따라 출력으로 전달되는 hidden state를 계산합니다.dictionary :MLGruCellOptions MLOperatorOptions {MLOperand bias ;MLOperand recurrentBias ;boolean resetAfter =true ;MLGruWeightLayout layout = "zrn";sequence <MLRecurrentNetworkActivation >activations ; };partial interface MLGraphBuilder {MLOperand gruCell (MLOperand input ,MLOperand weight ,MLOperand recurrentWeight ,MLOperand hiddenState , [EnforceRange ]unsigned long hiddenSize ,optional MLGruCellOptions options = {}); };dictionary {MLGruCellSupportLimits MLTensorLimits input ;MLTensorLimits weight ;MLTensorLimits recurrentWeight ;MLTensorLimits hiddenState ;MLTensorLimits bias ;MLTensorLimits recurrentBias ;MLTensorLimits output ; };partial dictionary MLOpSupportLimits {MLGruCellSupportLimits gruCell ; };
MLGruCellOptions
에는 다음 멤버가 있습니다.
bias, 유형은 MLOperand-
shape이 [3 * hiddenSize]인 1차원 입력 bias 텐서입니다. 텐서 shape의 두 번째 차원에서 bias 벡터의 순서는
layout에 따라 지정됩니다. recurrentBias, 유형은 MLOperand-
shape이 [3 * hiddenSize]인 1차원 recurrent bias 텐서입니다. 텐서 shape의 두 번째 차원에서 bias 벡터의 순서는
layout에 따라 지정됩니다. resetAfter, 유형은 boolean이며 기본값은true-
행렬 곱셈 후 또는 전에 reset gate를 적용할지를 나타냅니다.
layout, 유형은 MLGruWeightLayout이며 기본값은"zrn"-
GRU의 내부 gate에 대한 weight 및 bias 벡터의 순서로, 구체적으로
update (z),reset (r), 그리고new (n)gate이며, 이는 weight 및 bias 텐서 shape의 두 번째 차원에 표시됩니다. activations, 유형은 sequence<MLRecurrentNetworkActivation>-
첫 번째 함수는 update 및 reset gate에 사용되고 두 번째 함수는 new gate에 사용되는 한 쌍의 활성화 함수를 지정합니다. 지정되지 않은 경우 각각
"sigmoid"및"tanh"함수가 기본값입니다.
-
input:MLOperand입니다. shape이 [batchSize, inputSize]인 입력 2차원 텐서입니다. -
weight:MLOperand입니다. shape이 [3 * hiddenSize, inputSize]인 2차원 입력 weight 텐서입니다. 텐서 shape의 첫 번째 차원에서 weight 벡터의 순서는layout에 따라 지정됩니다. -
recurrentWeight:MLOperand입니다. shape이 [3 * hiddenSize, hiddenSize]인 2차원 recurrent weight 텐서입니다. 텐서 shape의 첫 번째 차원에서 weight 벡터의 순서는layout에 따라 지정됩니다. -
hiddenState:MLOperand입니다. shape이 [batchSize, hiddenSize]인 입력 2차원 hidden state 텐서입니다. -
hiddenSize:unsigned long스칼라입니다. 출력 텐서 shape의 두 번째 차원 값입니다. hidden state의 feature 수를 나타냅니다. -
options: 선택적MLGruCellOptions입니다. 연산의 선택적 매개변수입니다.
반환: MLOperand입니다.
shape이 [batchSize, hiddenSize]인 2차원 텐서로, 순환 네트워크의 단일 time
step에 대한 cell 출력 hidden state입니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
| "float32",
"float16"
| "float32",
"float16"
| 2 | 2 |
| 동일한 유형
| "float32",
"float16"
| 2 | 2 |
| 동일한 유형
| "float32",
"float16"
| 2 | 2 |
| 동일한 유형
| "float32",
"float16"
| 2 | 2 |
bias
| 동일한 유형
| "float32",
"float16"
| 1 | 1 |
recurrentBias
| 동일한 유형
| "float32",
"float16"
| 1 | 1 |
| 출력 | 동일한 유형
| "float32",
"float16"
| 2 | 2 |
MLGruCellSupportLimits
에는 다음 멤버가 있습니다;
input, 유형은 MLTensorLimits-
입력 피연산자에 대한
MLTensorLimits입니다. weight, 유형은 MLTensorLimits-
weight 피연산자에 대한
MLTensorLimits입니다. recurrentWeight, 유형은 MLTensorLimits-
recurrentWeight 피연산자에 대한
MLTensorLimits입니다. hiddenState, 유형은 MLTensorLimits-
hiddenState 피연산자에 대한
MLTensorLimits입니다. bias, 유형은 MLTensorLimits-
bias 피연산자에 대한
MLTensorLimits입니다. recurrentBias, 유형은 MLTensorLimits-
recurrentBias 피연산자에 대한
MLTensorLimits입니다. output, 유형은 MLTensorLimits-
출력 피연산자에 대한
MLTensorLimits입니다.
MLOpSupportLimits
에는 gruCell()에
대해 다음 멤버가 있습니다.
gruCell, 유형은 MLGruCellSupportLimits-
gruCell()연산자의 지원 제한입니다.
gruCell(input, weight, recurrentWeight, hiddenState, hiddenSize, options)
메서드의 단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input, weight, recurrentWeight, hiddenState, options.
bias(존재하는 경우), 그리고 options.recurrentBias(존재하는 경우) 중 하나가 false를 반환하면 예외를 발생시킵니다.TypeError입니다. -
input, weight, recurrentWeight, 또는 hiddenState 중 하나의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름) 예외를 발생시킵니다.
TypeError입니다. -
input, weight, recurrentWeight 또는 hiddenState 중 하나의 rank가 해당 허용되는 rank가 아니면(이 표에 따름) 예외를 발생시킵니다.
TypeError입니다. -
batchSize를 input의 shape[0]으로 둡니다.
-
inputSize를 input의 shape[1]로 둡니다.
-
weight의 shape이 « 3 * hiddenSize, inputSize »와 같지 않으면 예외를 발생시킵니다.
TypeError입니다. -
recurrentWeight의 shape이 « 3 * hiddenSize, hiddenSize »와 같지 않으면 예외를 발생시킵니다.
TypeError입니다. -
hiddenState의 shape이 « batchSize, hiddenSize »와 같지 않으면 예외를 발생시킵니다.
TypeError입니다. -
hiddenSize * 6이 유효한 차원이 아니면 예외를 발생시킵니다.
TypeError입니다.왜 hiddenSize * 6인가요?
일부 기반 플랫폼은bias와recurrentBias를 연결한 단일 bias 텐서에서 동작합니다. 따라서 3 * hiddenSize + 3 * hiddenSize 역시 유효한 차원이어야 합니다. -
options.
recurrentBias가 존재하면: -
options.
activations가 존재하면:-
activations를 options.
activations의 복제본으로 둡니다.
-
그렇지 않으면:
-
desc를 input의 dataType과 « batchSize, hiddenSize »가 주어진 상태에서 MLOperandDescriptor를 생성한 결과로 둡니다.
-
그래프 연결을 구성합니다.
-
output을 this와 desc가 주어진 상태에서 MLOperand를 생성한 결과로 둡니다.
-
operator를 weight, recurrentWeight, hiddenState, hiddenSize 및 options가 주어진 "gruCell" 연산에 대한 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input, weight, recurrentWeight, 그리고 hiddenState로 설정합니다.
-
options.
recurrentBias가 존재하면 이를 operator의 입력에 추가합니다. -
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
weight 레이아웃이 기본 "zrn"
레이아웃이고, update/reset gate 및 new gate의 활성화 함수가
각각 sigmoid()
및 tanh()
인 경우 이 연산의 동작은 다음과 같이 다른 연산을 사용하여 일반적으로 에뮬레이션할 수 있지만
사용자 에이전트에는 일반적으로 더 효율적인 구현이 있습니다. 기반 플랫폼이
연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로 사용할 수 있습니다.
function gruCell( builder, input, weight, recurrentWeight, hiddenState, hiddenSize, options) { const one= builder. constant( input. dataType, 1 ); const zero= builder. constant( input. dataType, 0 ); const inputSize= input. shape[ 1 ]; // update gate (z) let z= builder. sigmoid( builder. add( builder. add( ( options. bias? builder. slice( options. bias, [ 0 ], [ hiddenSize]) : zero), ( options. recurrentBias? builder. slice( options. recurrentBias, [ 0 ], [ hiddenSize]) : zero)), builder. add( builder. matmul( input, builder. transpose( builder. slice( weight, [ 0 , 0 ], [ hiddenSize, inputSize]))), builder. matmul( hiddenState, builder. transpose( builder. slice( recurrentWeight, [ 0 , 0 ], [ hiddenSize, hiddenSize])))))); // reset gate (r) let r= builder. sigmoid( builder. add( builder. add( ( options. bias? builder. slice( options. bias, [ hiddenSize], [ hiddenSize]) : zero), ( options. recurrentBias? builder. slice( options. recurrentBias, [ hiddenSize], [ hiddenSize]) : zero)), builder. add( builder. matmul( input, builder. transpose( builder. slice( weight, [ hiddenSize, 0 ], [ hiddenSize, inputSize]))), builder. matmul( hiddenState, builder. transpose( builder. slice( recurrentWeight, [ hiddenSize, 0 ], [ hiddenSize, hiddenSize])))))); // new gate (n) let n; if ( options. resetAfter) { n= builder. tanh( builder. add( ( options. bias? builder. slice( options. bias, [ 2 * hiddenSize], [ hiddenSize]) : zero), builder. add( builder. matmul( input, builder. transpose( builder. slice( weight, [ 2 * hiddenSize, 0 ], [ hiddenSize, inputSize]))), builder. mul( r, builder. add( ( options. recurrentBias? builder. slice( options. recurrentBias, [ 2 * hiddenSize], [ hiddenSize]) : zero), builder. matmul( hiddenState, builder. transpose( builder. slice( recurrentWeight, [ 2 * hiddenSize, 0 ], [ hiddenSize, hiddenSize])))))))); } else { n= builder. tanh( builder. add( builder. add( ( options. bias? builder. slice( options. bias, [ 2 * hiddenSize], [ hiddenSize]) : zero), ( options. recurrentBias? builder. slice( options. recurrentBias, [ 2 * hiddenSize], [ hiddenSize]) : zero)), builder. add( builder. matmul( input, builder. transpose( builder. slice( weight, [ 2 * hiddenSize, 0 ], [ hiddenSize, inputSize]))), builder. matmul( builder. mul( r, hiddenState), builder. transpose( builder. slice( recurrentWeight, [ 2 * hiddenSize, 0 ], [ hiddenSize, hiddenSize])))))); } // 새로운 hidden state를 계산합니다. return builder. add( builder. mul( z, hiddenState), builder. mul( n, builder. sub( one, z))); }
8.9.27. hardSigmoid
더 빠른 계산을 위해 sigmoid 함수 대신 사용하는 비평활 hard sigmoid 함수를 입력 텐서에 대해 계산합니다.dictionary :MLHardSigmoidOptions MLOperatorOptions {double alpha = 0.2;double beta = 0.5; };partial interface MLGraphBuilder {MLOperand hardSigmoid (MLOperand input ,optional MLHardSigmoidOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits hardSigmoid ; };
MLHardSigmoidOptions
에는 다음 멤버가 있습니다.
alpha, 유형은 double이며 기본값은0.2-
스칼라 배수입니다.
beta, 유형은 double이며 기본값은0.5-
스칼라 가산값입니다.
-
input:MLOperand입니다. 입력 텐서입니다. -
options: 선택적MLHardSigmoidOptions입니다. 연산의 선택적 매개변수입니다.
반환:
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
input
| "float32",
"float16"
| "float32",
"float16"
| N | 0에서 5까지 |
| 출력 | 동일한 유형 input
| "float32",
"float16"
| 동일한 rank input
| 0에서 5까지 |
MLOpSupportLimits
에는 hardSigmoid()에
대해 다음 멤버가 있습니다.
hardSigmoid, 유형은 MLSingleInputSupportLimits-
hardSigmoid()연산자의 지원 제한입니다.
hardSigmoid(input, options)
메서드의 단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input이 false를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
input의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름) 예외를 발생시킵니다.
TypeError입니다. -
options.
alpha를 options.alpha를 input의 dataType으로 캐스트한 결과로 설정합니다. -
options.
beta를 options.beta를 input의 dataType으로 캐스트한 결과로 설정합니다. -
그래프 연결을 구성합니다.
-
output을 input이 주어진 상태에서 MLOperand를 복사한 결과로 둡니다.
-
operator를 options가 주어진 "hardSigmoid" 연산에 대한 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
사용자 에이전트에는 일반적으로 더 효율적인 구현이 있지만, 이 연산의 동작은 다른 연산을 사용하여 다음과 같이 일반적으로 에뮬레이션할 수 있습니다. 기반 플랫폼이 연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로 사용할 수 있습니다.
function hardSigmoid( builder, input, options) { return builder. max( builder. min( builder. add( builder. mul( builder. constant( input. dataType, options. alpha), input), builder. constant( input. dataType, options. beta)), builder. constant( input. dataType, 1 )), builder. constant( input. dataType, 0 )); }
8.9.28. hardSwish
[MobileNetV3]에서 도입된 비선형 함수y = x * max(0, min(6, (x + 3))) / 6를
입력 텐서에 요소별로 계산합니다.
partial interface MLGraphBuilder {MLOperand hardSwish (MLOperand input ,optional MLOperatorOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits hardSwish ; };
-
input:MLOperand입니다. 입력 텐서입니다. -
options:MLOperatorOptions입니다. 연산의 선택적 매개변수를 지정합니다.
반환:
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
input
| "float32",
"float16"
| "float32",
"float16"
| N | 0에서 5까지 |
| 출력 | 동일한 유형 input
| "float32",
"float16"
| 동일한 rank input
| 0에서 5까지 |
MLOpSupportLimits
에는 hardSwish()에
대해 다음 멤버가 있습니다.
hardSwish, 유형은 MLSingleInputSupportLimits-
hardSwish()연산자의 지원 제한입니다.
hardSwish(input, options)
메서드의 단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input이 false를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
input의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름) 예외를 발생시킵니다.
TypeError입니다. -
그래프 연결을 구성합니다.
-
output을 input이 주어진 상태에서 MLOperand를 복사한 결과로 둡니다.
-
operator를 options가 주어진 "hardSwish" 연산에 대한 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
사용자 에이전트에는 일반적으로 더 효율적인 구현이 있지만, 이 연산의 동작은 다른 연산을 사용하여 다음과 같이 일반적으로 에뮬레이션할 수 있습니다. 기반 플랫폼이 연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로 사용할 수 있습니다.
function hardSwish( builder, input, options) { return builder. div( builder. mul( input, builder. max( builder. constant( input. dataType, 0 ), builder. min( builder. constant( input. dataType, 6 ), builder. add( input, builder. constant( input. dataType, 3 ))))), builder. constant( input. dataType, 6 )); }
8.9.29. instanceNormalization
[Instance-Normalization]을 사용하여 입력을 정규화합니다. 모델을 학습하는 동안 정규화에 사용되는 평균과 분산 값이 batch 차원의 모든 샘플에 걸쳐 계산되는batchNormalization()
과 달리, instance normalization에서 사용하는 평균과 분산 값은 batch의 각 개별 샘플의 각 입력 feature에 대해
즉석에서 계산됩니다.
dictionary :MLInstanceNormalizationOptions MLOperatorOptions {MLOperand scale ;MLOperand bias ;double epsilon = 1e-5;MLInputOperandLayout layout = "nchw"; };partial interface MLGraphBuilder {MLOperand instanceNormalization (MLOperand input ,optional MLInstanceNormalizationOptions options = {}); };dictionary {MLNormalizationSupportLimits MLTensorLimits input ;MLTensorLimits scale ;MLTensorLimits bias ;MLTensorLimits output ; };partial dictionary MLOpSupportLimits {MLNormalizationSupportLimits instanceNormalization ; };
MLInstanceNormalizationOptions
에는 다음 멤버가 있습니다.
scale, 유형은 MLOperand-
크기가 채널 수, 즉 입력 feature 차원의 크기와 같은 스케일링 값의 1차원 텐서입니다. 예를 들어
input텐서의 레이아웃이"nchw"인 경우 크기는input의 shape[1]과 같습니다. bias, 유형은 MLOperand-
크기가 입력 feature 차원의 크기와 같은 bias 값의 1차원 텐서입니다. 예를 들어
input텐서의 레이아웃이"nchw"인 경우 크기는input의 shape[1]과 같습니다. epsilon, 유형은 double이며 기본값은1e-5-
0으로 나누기로 인한 계산 오류를 방지하기 위한 작은 값입니다.
layout, 유형은 MLInputOperandLayout이며 기본값은"nchw"-
입력의 레이아웃 형식입니다.
-
input:MLOperand입니다. 입력 4차원 텐서입니다. -
options: 선택적MLInstanceNormalizationOptions입니다. 연산의 선택적 매개변수입니다.
반환: MLOperand입니다.
input과
동일한 shape을 가진 instance-normalized 4차원 텐서입니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
input
| "float32",
"float16"
| "float32",
"float16"
| 4 | 4 |
scale
| 동일한 유형 input
| "float32",
"float16"
| 1 | 1 |
bias
| 동일한 유형 input
| "float32",
"float16"
| 1 | 1 |
| 출력 | 동일한 유형 input
| "float32",
"float16"
| 4 | 4 |
MLNormalizationSupportLimits
에는 다음 멤버가 있습니다.
input, 유형은 MLTensorLimits-
입력 피연산자에 대한
MLTensorLimits입니다. scale, 유형은 MLTensorLimits-
scale 피연산자에 대한
MLTensorLimits입니다. bias, 유형은 MLTensorLimits-
bias 피연산자에 대한
MLTensorLimits입니다. output, 유형은 MLTensorLimits-
출력 피연산자에 대한
MLTensorLimits입니다.
MLOpSupportLimits
에는 instanceNormalization()에
대해 다음 멤버가 있습니다.
instanceNormalization, 유형은 MLNormalizationSupportLimits-
instanceNormalization()연산자의 지원 제한입니다.
instanceNormalization(input, options)
메서드의 단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input, options.
scale(존재하는 경우), 그리고 options.bias(존재하는 경우) 중 하나가 false를 반환하면 예외를 발생시킵니다.TypeError입니다. -
input의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름) 예외를 발생시킵니다.
TypeError입니다. -
options.
epsilon을 options.epsilon을 input의 dataType으로 캐스트한 결과로 설정합니다. -
그래프 연결을 구성합니다.
-
output을 반환합니다.
입력 텐서가 "nchw"
레이아웃의 4차원 텐서인 경우, 이 연산의 동작은 다른 연산을 사용하여 다음과 같이 일반적으로 에뮬레이션할 수 있지만 사용자
에이전트에는 일반적으로 더 효율적인 구현이 있습니다. 기반 플랫폼이
연산을 직접 지원하지 않는 경우 이 분해를
구현을 안내하는 템플릿으로 사용할 수 있습니다.
function instanceNormalization( builder, input, options) { // 평균 및 분산 값의 축소는 입력의 공간 // 차원, 예를 들어 입력 텐서의 축 2와 3에서 수행됩니다. const reduceOptions= { axes: [ 2 , 3 ], keepDimensions: true }; const mean= builder. reduceMean( input, reduceOptions); const variance= builder. reduceMean( builder. pow( builder. sub( input, mean), builder. constant( input. dataType, 2 )), reduceOptions); // scale 및 bias 값은 입력 feature별로 적용됩니다. // 예를 들어 입력 텐서의 축 1입니다. const shape= [ 1 , input. shape[ 1 ], 1 , 1 ]; return builder. add( builder. mul( builder. reshape( options. scale, shape), builder. div( builder. sub( input, mean), builder. sqrt( builder. add( variance, options. epsilon)))), builder. reshape( options. bias, shape)); }
8.9.30. layerNormalization
[Layer-Normalization]을 사용하여 입력을 정규화합니다. 모델을 학습하는 동안 평균과 분산 값이 batch 차원의 모든 샘플에 걸쳐 계산되는batchNormalization()
및 batch의 각 개별 샘플의 각 입력 feature에 대해 평균과 분산 값이 즉석에서 계산되는 instanceNormalization()
과 달리, layer normalization의 평균과 분산 값은 batch의 각 개별 샘플의 모든 입력
feature에 걸쳐 즉석에서 계산됩니다.
dictionary :MLLayerNormalizationOptions MLOperatorOptions {MLOperand scale ;MLOperand bias ;sequence <[EnforceRange ]unsigned long >axes ;double epsilon = 1e-5; };partial interface MLGraphBuilder {MLOperand layerNormalization (MLOperand input ,optional MLLayerNormalizationOptions options = {}); };partial dictionary MLOpSupportLimits {MLNormalizationSupportLimits layerNormalization ; };
MLLayerNormalizationOptions
에는 다음 멤버가 있습니다.
scale, 유형은 MLOperand-
axes멤버에 의해 shape이 결정되는 스케일링 값의 N차원 텐서이며,axes의 각 값은 스케일링 값이 있는 입력 텐서의 차원을 나타냅니다. 예를 들어axes값이 [1,2,3]이면 이 텐서의 shape은 입력 차원 1, 2 및 3의 대응하는 크기 목록입니다. 이 멤버가 없으면 스케일링 값은 1로 간주됩니다. bias, 유형은 MLOperand-
axes멤버에 의해 shape이 결정되는 bias 값의 N차원 텐서이며,axes의 각 값은 bias 값이 있는 입력 텐서의 차원을 나타냅니다. 예를 들어axes값이 [1,2,3]이면 이 텐서의 shape은 입력 차원 1, 2 및 3의 대응하는 크기 목록입니다. 이 멤버가 없으면 bias 값은 0으로 간주됩니다. axes, 유형은sequence<[EnforceRange] unsigned long>-
축소할 입력 차원의 인덱스입니다. 이 멤버가 없으면 첫 번째 차원을 제외한 모든 차원이 지정된 것으로 처리됩니다(예: 4차원 입력 텐서의 경우
axes= [1,2,3]). 즉, 평균과 분산 값에 대한 축소는 각 독립적인 batch의 모든 입력 feature에 걸쳐 계산됩니다. 비어 있으면 어떤 차원도 축소하지 않습니다. epsilon, 유형은 double이며 기본값은1e-5-
0으로 나누기로 인한 계산 오류를 방지하기 위한 작은 값입니다.
-
input:MLOperand입니다. 입력 N차원 텐서입니다. -
options: 선택적MLLayerNormalizationOptions입니다. 연산의 선택적 매개변수입니다.
반환: MLOperand입니다.
input과
동일한 shape을 가진 layer-normalized N차원 텐서입니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
input
| "float32",
"float16"
| "float32",
"float16"
| N | 0에서 5까지 |
scale
| 동일한 유형 input
| "float32",
"float16"
| N | 0에서 5까지 |
bias
| 동일한 유형 input
| "float32",
"float16"
| N | 0에서 5까지 |
| 출력 | 동일한 유형 input
| "float32",
"float16"
| 동일한 rank input
| 0에서 5까지 |
MLOpSupportLimits
에는 layerNormalization()에
대해 다음 멤버가 있습니다.
layerNormalization, 유형은 MLNormalizationSupportLimits-
layerNormalization()연산자의 지원 제한입니다.
layerNormalization(input, options)
메서드의 단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input, options.
scale(존재하는 경우), 그리고 options.bias(존재하는 경우) 중 하나가 false를 반환하면 예외를 발생시킵니다.TypeError입니다. -
input의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름) 예외를 발생시킵니다.
TypeError입니다. -
options.
axes가 존재하지 않으면 options.axes를 새 목록으로 설정합니다. input의 rank가 1보다 크면 1부터 input의 rank까지의 범위(상한 제외)로 하고, 그렇지 않으면 빈 목록으로 합니다. -
그렇지 않고 options.
axes에 중복 값이 포함되어 있거나 그 항목 중 하나라도 0부터 input의 rank까지의 범위(상한 제외)에 없으면 예외를 발생시킵니다.TypeError입니다. -
options.
epsilon을 options.epsilon을 input의 dataType으로 캐스트한 결과로 설정합니다. -
그래프 연결을 구성합니다.
-
output을 반환합니다.
axes 매개변수가 [1,2,3]으로 설정된 경우 이 연산의 동작은 다른 연산을 사용하여 다음과 같이 일반적으로 에뮬레이션할 수 있지만 사용자 에이전트에는 일반적으로 더 효율적인 구현이 있습니다. 기반 플랫폼이 연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로 사용할 수 있습니다.
function layerNormalization( builder, input, options) { // 평균 및 분산 값의 축소는 입력의 모든 feature // (즉, 모든 채널)에 걸친 공간 차원에서 수행됩니다. // 텐서입니다. const reduceOptions= { axes: [ 1 , 2 , 3 ], keepDimensions: true }; const mean= builder. reduceMean( input, reduceOptions); const variance= builder. reduceMean( builder. pow( builder. sub( input, mean), builder. constant( input. dataType, 2 )), reduceOptions); // scale 및 bias 텐서는 입력의 shape 중 // axes 매개변수의 값(즉 [1,2,3])으로 지정된 shape을 가집니다. return builder. add( builder. mul( options. scale, builder. div( builder. sub( input, mean), builder. sqrt( builder. add( variance, options. epsilon)))), options. bias); }
8.9.31. leakyRelu
입력 텐서에 대해 요소별로 정류 선형 함수의 leaky 버전을 계산합니다. 계산은 다음 식을 따릅니다.max(0, x) + alpha * min(0, x).
dictionary :MLLeakyReluOptions MLOperatorOptions {double alpha = 0.01; };partial interface MLGraphBuilder {MLOperand leakyRelu (MLOperand input ,optional MLLeakyReluOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits leakyRelu ; };
MLLeakyReluOptions
에는 다음 멤버가 있습니다.
alpha, 유형은 double이며 기본값은0.01-
스칼라 배수입니다.
-
input:MLOperand입니다. 입력 텐서입니다. -
options: 선택적MLLeakyReluOptions입니다. 연산의 선택적 매개변수입니다.
반환:
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
input
| "float32",
"float16"
| "float32",
"float16"
| N | 0에서 5까지 |
| 출력 | 동일한 유형 input
| "float32",
"float16"
| 동일한 rank input
| 0에서 5까지 |
MLOpSupportLimits
에는 leakyRelu()에
대해 다음 멤버가 있습니다.
leakyRelu, 유형은 MLSingleInputSupportLimits-
leakyRelu()연산자의 지원 제한입니다.
leakyRelu(input, options)
메서드의 단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input이 false를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
input의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름) 예외를 발생시킵니다.
TypeError입니다. -
options.
alpha를 options.alpha를 input의 dataType으로 캐스트한 결과로 설정합니다. -
그래프 연결을 구성합니다.
-
output을 input이 주어진 상태에서 MLOperand를 복사한 결과로 둡니다.
-
operator를 options가 주어진 "leakyRelu" 연산에 대한 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
사용자 에이전트에는 일반적으로 더 효율적인 구현이 있지만, 이 연산의 동작은 다른 연산을 사용하여 다음과 같이 일반적으로 에뮬레이션할 수 있습니다. 기반 플랫폼이 연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로 사용할 수 있습니다.
function leakyRelu( builder, input, options) { return builder. add( builder. max( builder. constant( input. dataType, 0 ), input), builder. mul( builder. constant( input. dataType, options. alpha), builder. min( builder. constant( input. dataType, 0 ), input))); }
8.9.32. linear
입력 텐서에 대해 선형 함수y = alpha * x + beta를 계산합니다.
dictionary :MLLinearOptions MLOperatorOptions {double alpha = 1;double beta = 0; };partial interface MLGraphBuilder {MLOperand linear (MLOperand input ,optional MLLinearOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits linear ; };
MLLinearOptions
에는 다음 멤버가 있습니다.
alpha, 유형은 double이며 기본값은1-
스칼라 배수입니다.
beta, 유형은 double이며 기본값은0-
스칼라 가산값입니다.
-
input:MLOperand입니다. 입력 텐서입니다. -
options: 선택적MLLinearOptions입니다. 연산의 선택적 매개변수입니다.
반환:
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
input
| "float32",
"float16"
| "float32",
"float16"
| N | 0에서 5까지 |
| 출력 | 동일한 유형 input
| "float32",
"float16"
| 동일한 rank input
| 0에서 5까지 |
MLOpSupportLimits
에는 linear()에
대해 다음 멤버가 있습니다.
linear, 유형은 MLSingleInputSupportLimits-
linear()연산자의 지원 제한입니다.
linear(input, options)
메서드의 단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input이 false를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
input의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름) 예외를 발생시킵니다.
TypeError입니다. -
options.
alpha를 options.alpha를 input의 dataType으로 캐스트한 결과로 설정합니다. -
options.
beta를 options.beta를 input의 dataType으로 캐스트한 결과로 설정합니다. -
그래프 연결을 구성합니다.
-
output을 input이 주어진 상태에서 MLOperand를 복사한 결과로 둡니다.
-
operator를 options가 주어진 "linear" 연산에 대한 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
사용자 에이전트에는 일반적으로 더 효율적인 구현이 있지만, 이 연산의 동작은 다른 연산을 사용하여 다음과 같이 일반적으로 에뮬레이션할 수 있습니다. 기반 플랫폼이 연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로 사용할 수 있습니다.
function linear( builder, input, options) { return builder. add( builder. mul( input, builder. constant( input. dataType, options. alpha)), builder. constant( input. dataType, options. beta)); }
8.9.33. lstm
Long Short-Term Memory [LSTM] 순환 네트워크는 input, output, forget 및 cell gate를 사용하여 네트워크의 시간적 시퀀스를 따라 출력으로 전달되는 출력 상태를 계산합니다.enum {MLLstmWeightLayout , // input-output-forget-cell gate 순서"iofg" // input-forget-cell-output gate 순서 };"ifgo" dictionary :MLLstmOptions MLOperatorOptions {MLOperand bias ;MLOperand recurrentBias ;MLOperand peepholeWeight ;MLOperand initialHiddenState ;MLOperand initialCellState ;boolean returnSequence =false ;MLRecurrentNetworkDirection direction = "forward";MLLstmWeightLayout layout = "iofg";sequence <MLRecurrentNetworkActivation >activations ; };partial interface MLGraphBuilder {sequence <MLOperand >lstm (MLOperand input ,MLOperand weight ,MLOperand recurrentWeight , [EnforceRange ]unsigned long steps , [EnforceRange ]unsigned long hiddenSize ,optional MLLstmOptions options = {}); };dictionary {MLLstmSupportLimits MLTensorLimits input ;MLTensorLimits weight ;MLTensorLimits recurrentWeight ;MLTensorLimits bias ;MLTensorLimits recurrentBias ;MLTensorLimits peepholeWeight ;MLTensorLimits initialHiddenState ;MLTensorLimits initialCellState ;MLTensorLimits output0 ;MLTensorLimits output1 ;MLTensorLimits output2 ; };partial dictionary MLOpSupportLimits {MLLstmSupportLimits lstm ; };
MLLstmOptions
에는 다음 멤버가 있습니다.
bias, 유형은 MLOperand-
shape이 [numDirections, 4 * hiddenSize]인 2차원 입력 bias 텐서입니다. 텐서 shape의 두 번째 차원에서 bias 벡터의 순서는
layout에 따라 지정됩니다. recurrentBias, 유형은 MLOperand-
shape이 [numDirections, 4 * hiddenSize]인 2차원 recurrent bias 텐서입니다. 텐서 shape의 첫 번째 차원에서 bias 벡터의 순서는
layout에 따라 지정됩니다. peepholeWeight, 유형은 MLOperand-
shape이 [numDirections, 3 * hiddenSize]인 peephole용 2차원 weight 텐서입니다. weight 벡터의 패킹 순서는 각각
input (i),output (o), 그리고forget (f)gate입니다. initialHiddenState, 유형은 MLOperand-
shape이 [numDirections, batchSize, hiddenSize]인 3차원 초기 hidden state 텐서입니다. 지정되지 않은 경우 구현은 반드시 0으로 채운 텐서를 사용해야 합니다.
initialCellState, 유형은 MLOperand-
shape이 [numDirections, batchSize, hiddenSize]인 3차원 초기 hidden state 텐서입니다. 지정되지 않은 경우 구현은 반드시 0으로 채운 텐서를 사용해야 합니다.
returnSequence, 유형은 boolean이며 기본값은false-
마지막 time step의 출력과 더불어 각 time step의 모든 출력을 포함하는 전체 시퀀스도 반환할지를 나타냅니다.
direction, 유형은 MLRecurrentNetworkDirection이며 기본값은"forward"-
입력 시퀀스의 처리 방향입니다.
"both"로 설정하면 weight 및 bias 텐서 shape의 첫 번째 차원 크기는 반드시 2여야 하며, 입력은 양방향으로 처리됩니다. layout, 유형은 MLLstmWeightLayout이며 기본값은"iofg"-
LSTM의 내부 gate에 대한 weight 및 bias 벡터의 순서로, 구체적으로
input (i),output (o),forget (f), 그리고cell (g)gate이며, 이는 weight 및 bias 텐서 shape의 첫 번째 차원에 표시됩니다. activations, 유형은 sequence<MLRecurrentNetworkActivation>-
세 개의 활성화 함수 목록입니다. 첫 번째 함수는
input (i),forget (f), 그리고output (o)gate에 사용되고, 두 번째 함수는cell (g)gate에 사용되며, 마지막 함수는 출력 hidden state를 형성하기 위해 output gate의 결과와 결합하기 전에 출력 cell state를 필터링하는 데 사용됩니다. 지정되지 않은 경우 각각"sigmoid","tanh", 그리고"tanh"함수의 시퀀스가 기본값입니다.
-
input:MLOperand입니다. shape이 [steps, batchSize, inputSize]인 입력 3차원 텐서입니다. -
weight:MLOperand입니다. shape이 [numDirections, 4 * hiddenSize, inputSize]인 3차원 입력 weight 텐서입니다. 텐서 shape의 두 번째 차원에서 weight 벡터의 순서는layout에 따라 지정됩니다. -
recurrentWeight:MLOperand입니다. shape이 [numDirections, 4 * hiddenSize, hiddenSize]인 3차원 recurrent weight 텐서입니다. 텐서 shape의 두 번째 차원에서 weight 벡터의 순서는layout에 따라 지정됩니다. -
steps:unsigned long스칼라입니다. 순환 네트워크의 time step 수입니다. 값은 0보다 커야 합니다. -
hiddenSize:unsigned long스칼라입니다. cell 출력 텐서 shape의 세 번째 차원 값입니다. hidden state의 feature 수를 나타냅니다. -
options: 선택적MLLstmOptions입니다. 연산의 선택적 매개변수입니다.
반환: sequence<MLOperand>.
첫 번째 요소는 shape이 [numDirections, batchSize, hiddenSize]인 3차원 텐서로, 네트워크의
마지막 time step에서의 출력 hidden state입니다. 두 번째 요소는 shape이
[numDirections, batchSize, hiddenSize]인 3차원 텐서로, 네트워크의 마지막 time step에서의
출력 cell state입니다. 또한 returnSequence
가 true로 설정된 경우 세 번째 요소는 shape이 [steps, numDirections,
batchSize, hiddenSize]인 4차원 출력 텐서이며 시간적 시퀀스의 각 time step에서 나온 모든 출력을 포함합니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 rank | 필수 rank |
|---|---|---|---|---|
| "float32",
"float16"
| "float32",
"float16"
| 3 | 3 |
| 동일한 유형
| "float32",
"float16"
| 3 | 3 |
| 동일한 유형
| "float32",
"float16"
| 3 | 3 |
bias
| 동일한 유형
| "float32",
"float16"
| 2 | 2 |
recurrentBias
| 동일한 유형
| "float32",
"float16"
| 2 | 2 |
peepholeWeight
| 동일한 유형
| "float32",
"float16"
| 2 | 2 |
| 동일한 유형
| "float32",
"float16"
| 3 | 3 |
initialCellState
| 동일한 유형
| "float32",
"float16"
| 3 | 3 |
| outputs[0] | 동일한 유형
| "float32",
"float16"
| 3 | 3 |
| outputs[1] | 동일한 유형
| "float32",
"float16"
| 3 | 3 |
outputs[2] if returnSequence
가 true인 경우
| 동일한 유형
| "float32",
"float16"
| 4 | 4 |
MLLstmSupportLimits
에는 다음 멤버가 있습니다.
input, 유형은 MLTensorLimits-
입력 피연산자에 대한
MLTensorLimits입니다. weight, 유형은 MLTensorLimits-
weight 피연산자에 대한
MLTensorLimits입니다. recurrentWeight, 유형은 MLTensorLimits-
recurrentWeight 피연산자에 대한
MLTensorLimits입니다. bias, 유형은 MLTensorLimits-
bias 피연산자에 대한
MLTensorLimits입니다. recurrentBias, 유형은 MLTensorLimits-
recurrentBias 피연산자에 대한
MLTensorLimits입니다. peepholeWeight, 유형은 MLTensorLimits-
peepholeWeight 피연산자에 대한
MLTensorLimits입니다. initialHiddenState, 유형은 MLTensorLimits-
initialHiddenState 피연산자에 대한
MLTensorLimits입니다. initialCellState, 유형은 MLTensorLimits-
initialCellState 피연산자에 대한
MLTensorLimits입니다. output0, 유형은 MLTensorLimits-
모든 출력 피연산자[0]에 대한
MLTensorLimits입니다. output1, 유형은 MLTensorLimits-
모든 출력 피연산자[1]에 대한
MLTensorLimits입니다. output2, 유형은 MLTensorLimits-
모든 출력 피연산자[2]에 대한
MLTensorLimits입니다.
MLOpSupportLimits
에는 lstm()에
대해 다음 멤버가 있습니다.
lstm, 유형은 MLLstmSupportLimits-
lstm()연산자의 지원 제한입니다.
lstm(input, weight, recurrentWeight, steps, hiddenSize, options)
메서드의 단계는 다음과 같습니다.
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input, weight, recurrentWeight, options.
bias(존재하는 경우), options.recurrentBias(존재하는 경우), options.peepholeWeight(존재하는 경우), options.(존재하는 경우), 그리고 options.initialCellState(존재하는 경우) 중 하나가 false를 반환하면 예외를 발생시킵니다.TypeError입니다. -
numDirections를 options.
direction이"both"이면 2로, 그렇지 않으면 1로 둡니다. -
input, weight 또는 recurrentWeight 중 하나의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름) 예외를 발생시킵니다.
TypeError입니다. -
input, weight 또는 recurrentWeight 중 하나의 rank가 해당 허용되는 rank가 아니면 예외를 발생시킵니다.
TypeError입니다. -
batchSize를 input의 shape[1]로 둡니다.
-
inputSize를 input의 shape[2]로 둡니다.
-
weight의 shape이 « numDirections, 4 * hiddenSize, inputSize »와 같지 않으면 예외를 발생시킵니다.
TypeError입니다. -
recurrentWeight의 shape이 « numDirections, 4 * hiddenSize, hiddenSize »와 같지 않으면 예외를 발생시킵니다.
TypeError입니다. -
hiddenSize * 8이 유효한 차원이 아니면 예외를 발생시킵니다.
TypeError입니다.왜 hiddenSize * 8인가요?
일부 기반 플랫폼은bias와recurrentBias를 연결한 단일 bias 텐서에서 동작합니다. 따라서 4 * hiddenSize + 4 * hiddenSize 역시 유효한 차원이어야 합니다. -
options.
recurrentBias가 존재하면: -
options.
peepholeWeight가 존재하면: -
options.
가 존재하면: -
options.
initialCellState가 존재하면: -
options.
activations가 존재하면:-
activations를 options.
activations의 복제본으로 둡니다.
-
그렇지 않으면:
-
출력 shape을 계산합니다.
-
desc를 input의 dataType과 « numDirections, batchSize, hiddenSize »가 주어진 상태에서 MLOperandDescriptor를 생성한 결과로 둡니다.
-
options.
returnSequence가 true이면:-
desc2를 input의 dataType 과 « steps, numDirections, batchSize, hiddenSize »가 주어진 상태에서 MLOperandDescriptor를 생성한 결과로 둡니다.
-
-
-
그래프 연결을 구성합니다.
-
operator를 weight, recurrentWeight, steps, hiddenSize 및 options가 주어진 "lstm" 연산에 대한 연산자로 둡니다.
-
output0을 this와 desc가 주어진 상태에서 MLOperand를 생성한 결과로 둡니다.
-
output1을 this와 desc가 주어진 상태에서 MLOperand를 생성한 결과로 둡니다.
-
options.
returnSequence가 true이면:-
output2를 this 와 desc2가 주어진 상태에서 MLOperand를 생성한 결과로 둡니다.
-
output을 목록 « output0, output1, output2 »로 둡니다.
-
output0.
[[operator]], output1.[[operator]]및 output2.[[operator]]를 operator로 설정합니다.
-
-
그렇지 않으면:
-
output을 목록 « output0, output1 »로 둡니다.
-
output0.
[[operator]]및 output1.[[operator]]를 operator로 설정합니다.
-
-
operator의 입력을 input, weight, 그리고 recurrentWeight로 설정합니다.
-
options.
recurrentBias가 존재하면 이를 operator의 입력에 추가합니다. -
options.
peepholeWeight가 존재하면 이를 operator의 입력에 추가합니다. -
options.
initialCellState가 존재하면 이를 operator의 입력에 추가합니다. -
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
squeeze() 헬퍼를 사용하면, 사용자 에이전트에는 일반적으로 더 효율적인 구현이 있지만 이 연산의 동작을 다른 연산을 사용하여 다음과 같이 일반적으로 에뮬레이션할 수 있습니다. 기반 플랫폼이 연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로 사용할 수 있습니다.
function lstm( builder, input, weight, recurrentWeight, steps, hiddenSize, options) { const batchSize= input. shape[ 1 ]; const inputSize= input. shape[ 2 ]; const direction= options. direction|| 'forward' ; const numDirections= ( direction== 'both' ? 2 : 1 ); let hiddenState= options. initialHiddenState; let cellState= options. initialCellState; if ( ! hiddenState) { const desc= { dataType: 'float32' , shape: [ numDirections, batchSize, hiddenSize] }; const totalSize= numDirections* batchSize* hiddenSize; hiddenState= builder. constant( desc, new Float32Array( totalSize). fill( 0 )); } if ( ! cellState) { const desc= { dataType: 'float32' , shape: [ numDirections, batchSize, hiddenSize] }; const totalSize= numDirections* batchSize* hiddenSize; cellState= builder. constant( desc, new Float32Array( totalSize). fill( 0 )); } let currentWeight= []; let currentRecurrentWeight= []; let currentBias= []; let currentRecurrentBias= []; let currentPeepholeWeight= []; let forwardSequence= null ; let backwardSequence= null ; let outputHidden= null ; let outputCell= null ; for ( let dir= 0 ; dir< numDirections; ++ dir) { currentWeight. push( squeeze( builder, builder. slice( weight, [ dir, 0 , 0 ], [ 1 , 4 * hiddenSize, inputSize]))); currentRecurrentWeight. push( squeeze( builder, builder. slice( recurrentWeight, [ dir, 0 , 0 ], [ 1 , 4 * hiddenSize, hiddenSize]))); currentBias. push( options. bias? ( squeeze( builder, builder. slice( options. bias, [ dir, 0 ], [ 1 , 4 * hiddenSize]))) : null ); currentRecurrentBias. push( options. recurrentBias? ( squeeze( builder, builder. slice( options. recurrentBias, [ dir, 0 ], [ 1 , 4 * hiddenSize]))) : null ); currentPeepholeWeight. push( options. peepholeWeight? ( squeeze( builder, builder. slice( options. peepholeWeight, [ dir, 0 ], [ 1 , 3 * hiddenSize]))) : null ); let currentHidden= squeeze( builder, builder. slice( hiddenState, [ dir, 0 , 0 ], [ 1 , batchSize, hiddenSize]), [ 0 ]); let currentCell= squeeze( builder, builder. slice( cellState, [ dir, 0 , 0 ], [ 1 , batchSize, hiddenSize]), [ 0 ]); for ( let step= 0 ; step< steps; ++ step) { const slice= ( dir== 1 || direction== 'backward' ? steps- step- 1 : step); const currentInput= squeeze( builder, builder. slice( input, [ slice, 0 , 0 ], [ 1 , batchSize, inputSize]), [ 0 ]); [ currentHidden, currentCell] = builder. lstmCell( currentInput, currentWeight[ dir], currentRecurrentWeight[ dir], currentHidden, currentCell, hiddenSize, { bias: currentBias[ dir], recurrentBias: currentRecurrentBias[ dir], peepholeWeight: currentPeepholeWeight[ dir], layout: options. layout, activations: options. activations}); if ( options. returnSequence) { // 2차원([batchSize, hiddenSize])인 currentHidden을 확장합니다. // 4차원([steps, numDirections, batchSize, hiddenSize])으로 const expandedHiddenAs4D= builder. reshape( currentHidden, [ 1 , 1 , batchSize, hiddenSize]); if ( direction== 'forward' || ( dir== 0 && direction== 'both' )) { forwardSequence= forwardSequence? builder. concat([ forwardSequence, expandedHiddenAs4D], 0 ) : expandedHiddenAs4D; } else if ( direction== 'backward' || ( dir== 1 && direction== 'both' )) { backwardSequence= backwardSequence? builder. concat([ expandedHiddenAs4D, backwardSequence], 0 ) : expandedHiddenAs4D; } } } // 2차원([batchSize, hiddenSize])인 currentHidden을 확장합니다. // 3차원([numDirections, batchSize, hiddenSize])으로 const expandedHiddenAs3D= builder. reshape( currentHidden, [ 1 , batchSize, hiddenSize]); outputHidden= outputHidden? builder. concat([ outputHidden, expandedHiddenAs3D], 0 ) : expandedHiddenAs3D; // 2차원([batchSize, hiddenSize])인 currentCell을 확장합니다. // 3차원([numDirections, batchSize, hiddenSize])으로 const expandedCellAs3D= builder. reshape( currentCell, [ 1 , batchSize, hiddenSize]); outputCell= outputCell? builder. concat([ outputCell, expandedCellAs3D], 0 ) : expandedCellAs3D; } if ( options. returnSequence) { let outputSequence= null ; if ( direction== 'forward' ) { outputSequence= forwardSequence; } else if ( direction== 'backward' ) { outputSequence= backwardSequence; } else if ( direction== 'both' ) { // 축 1을 따라 연결합니다(numDirections 차원). outputSequence= builder. concat([ forwardSequence, backwardSequence], 1 ); } return [ outputHidden, outputCell, outputSequence]; } else { return [ outputHidden, outputCell]; } }
8.9.34. lstmCell
셀 상태, 입력, 출력 및 망각 gate를 사용하여 셀 상태와 다음 타임 스텝의 은닉 상태를 계산하고, 이 상태가 네트워크의 시간적 시퀀스에 걸쳐 출력으로 전달되는 Long Short-Term Memory [LSTM] 순환 네트워크의 단일 타임 스텝입니다.dictionary :MLLstmCellOptions MLOperatorOptions {MLOperand bias ;MLOperand recurrentBias ;MLOperand peepholeWeight ;MLLstmWeightLayout layout = "iofg";sequence <MLRecurrentNetworkActivation >activations ; };partial interface MLGraphBuilder {sequence <MLOperand >lstmCell (MLOperand input ,MLOperand weight ,MLOperand recurrentWeight ,MLOperand hiddenState ,MLOperand cellState , [EnforceRange ]unsigned long hiddenSize ,optional MLLstmCellOptions options = {}); };dictionary {MLLstmCellSupportLimits MLTensorLimits input ;MLTensorLimits weight ;MLTensorLimits recurrentWeight ;MLTensorLimits hiddenState ;MLTensorLimits cellState ;MLTensorLimits bias ;MLTensorLimits recurrentBias ;MLTensorLimits peepholeWeight ;MLTensorLimits output0 ;MLTensorLimits output1 ; };partial dictionary MLOpSupportLimits {MLLstmCellSupportLimits lstmCell ; };
MLLstmCellOptions
에는 다음 멤버가 있습니다:
bias, 유형은 MLOperand-
shape이 [4 * hiddenSize]인 1차원 입력 bias 텐서입니다. 텐서 shape의 첫 번째 차원에서 bias 벡터의 순서는
layout에 따라 지정됩니다. recurrentBias, 유형은 MLOperand-
shape이 [4 * hiddenSize]인 1차원 순환 bias 텐서입니다. 텐서 shape의 첫 번째 차원에서 bias 벡터의 순서는
layout에 따라 지정됩니다. peepholeWeight, 유형은 MLOperand-
shape이 [3 * hiddenSize]인 peephole용 1차원 weight 텐서입니다. weight 벡터의 패킹 순서는 각각
input (i),output (o), 그리고forget (f)gate입니다. layout, 유형은 MLLstmWeightLayout이며 기본값은"iofg"-
LSTM 내부 gate의 weight 및 bias 벡터 순서로, 구체적으로
input (i),output (o),forget (f), 그리고cell (g)gate이며, weight 및 bias 텐서 shape의 첫 번째 차원에 표시됩니다. activations, 유형은 sequence<MLRecurrentNetworkActivation>-
세 개의 활성화 함수 목록입니다. 첫 번째 함수는
input (i),forget (f), 그리고output (o)gate에 사용되고, 두 번째 함수는cell (g)gate에 사용되며, 마지막 함수는 출력 은닉 상태를 만들기 위해 출력 gate의 결과와 결합하기 전에 출력 셀 상태를 필터링하는 데 사용됩니다. 지정하지 않으면 각각"sigmoid","tanh", 그리고"tanh"함수의 시퀀스가 기본값입니다.
-
input:MLOperand입니다. shape이 [batchSize, inputSize]인 입력 2차원 텐서입니다. -
weight:MLOperand입니다. shape이 [4 * hiddenSize, inputSize]인 2차원 입력 weight 텐서입니다. 텐서 shape의 첫 번째 차원에서 weight 벡터의 순서는layout에 따라 지정됩니다. -
recurrentWeight:MLOperand입니다. shape이 [4 * hiddenSize, hiddenSize]인 2차원 순환 weight 텐서입니다. 텐서 shape의 첫 번째 차원에서 weight 벡터의 순서는layout에 따라 지정됩니다. -
hiddenState:MLOperand입니다. shape이 [batchSize, hiddenSize]인 입력 2차원 은닉 상태 텐서입니다. -
cellState:MLOperand입니다. shape이 [batchSize, hiddenSize]인 입력 2차원 셀 상태 텐서입니다. -
hiddenSize:unsigned long스칼라입니다. 출력 텐서 shape의 두 번째 차원 값입니다. 은닉 상태의 feature 수를 나타냅니다. -
options: 선택적MLLstmCellOptions입니다. 연산의 선택적 매개변수입니다.
반환: sequence<MLOperand>.
첫 번째 요소는 순환 네트워크의 현재 타임 스텝의 출력 은닉 상태입니다.
다음 요소는 출력 셀 상태입니다. 두 요소 모두 shape이 [batchSize,
hiddenSize]인 2차원 텐서입니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
| "float32",
"float16"
| "float32",
"float16"
| 2 | 2 |
| 동일한 유형
| "float32",
"float16"
| 2 | 2 |
| 동일한 유형
| "float32",
"float16"
| 2 | 2 |
| 동일한 유형
| "float32",
"float16"
| 2 | 2 |
| 동일한 유형
| "float32",
"float16"
| 2 | 2 |
bias
| 동일한 유형
| "float32",
"float16"
| 1 | 1 |
recurrentBias
| 동일한 유형
| "float32",
"float16"
| 1 | 1 |
peepholeWeight
| 동일한 유형
| "float32",
"float16"
| 1 | 1 |
| outputs[0] | 동일한 유형
| "float32",
"float16"
| 2 | 2 |
| outputs[1] | 동일한 유형
| "float32",
"float16"
| 2 | 2 |
MLLstmCellSupportLimits
에는 다음 멤버가 있습니다:
input, 유형은 MLTensorLimits-
MLTensorLimits입력 피연산자에 대한 것입니다. weight, 유형은 MLTensorLimits-
MLTensorLimitsweight 피연산자에 대한 것입니다. recurrentWeight, 유형은 MLTensorLimits-
MLTensorLimitsrecurrentWeight 피연산자에 대한 것입니다. hiddenState, 유형은 MLTensorLimits-
MLTensorLimitshiddenState 피연산자에 대한 것입니다. cellState, 유형은 MLTensorLimits-
MLTensorLimitscellState 피연산자에 대한 것입니다. bias, 유형은 MLTensorLimits-
MLTensorLimitsbias 피연산자에 대한 것입니다. recurrentBias, 유형은 MLTensorLimits-
MLTensorLimitsrecurrentBias 피연산자에 대한 것입니다. peepholeWeight, 유형은 MLTensorLimits-
MLTensorLimitspeepholeWeight 피연산자에 대한 것입니다. output0, 유형은 MLTensorLimits-
MLTensorLimits모든 출력 피연산자[0]에 대한 것입니다. output1, 유형은 MLTensorLimits-
MLTensorLimits모든 출력 피연산자[1]에 대한 것입니다.
MLOpSupportLimits
에는 lstmCell()에
대해 다음 멤버가 있습니다:
lstmCell, 유형은 MLLstmCellSupportLimits-
lstmCell()연산자의 지원 제한입니다.
lstmCell(input, weight, recurrentWeight, hiddenState, cellState, hiddenSize, options)
메서드 단계는 다음과 같습니다:
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input, weight, recurrentWeight, hiddenState, cellState, options.
bias(존재하는 경우), options.recurrentBias(존재하는 경우), 그리고 options.peepholeWeight(존재하는 경우) 중 하나가 false를 반환하면 예외를 발생시킵니다.TypeError입니다. -
input, weight, recurrentWeight, hiddenState 또는 cellState 중 하나의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름) 예외를 발생시킵니다.
TypeError입니다. -
input, weight, recurrentWeight, hiddenState 또는 cellState 중 하나의 랭크가 해당 허용되는 랭크가 아니면 예외를 발생시킵니다.
TypeError입니다. -
batchSize를 input의 shape[0]으로 둡니다.
-
inputSize를 input의 shape[1]로 둡니다.
-
weight의 shape이 « 4 * hiddenSize, inputSize »와 같지 않으면 예외를 발생시킵니다.
TypeError입니다. -
recurrentWeight의 shape이 « 4 * hiddenSize, hiddenSize »와 같지 않으면 예외를 발생시킵니다.
TypeError입니다. -
hiddenState의 shape이 « batchSize, hiddenSize »와 같지 않으면 예외를 발생시킵니다.
TypeError입니다. -
cellState의 shape이 « batchSize, hiddenSize »와 같지 않으면 예외를 발생시킵니다.
TypeError입니다. -
hiddenSize * 8이 유효한 차원이 아니면 예외를 발생시킵니다.
TypeError입니다.왜 hiddenSize * 8인가요?
일부 기반 플랫폼은bias와recurrentBias를 연결한 단일 bias 텐서에서 동작합니다. 따라서 4 * hiddenSize + 4 * hiddenSize 역시 유효한 차원이어야 합니다. -
options.
recurrentBias가 존재하면: -
options.
peepholeWeight가 존재하면: -
options.
activations가 존재하면:-
activations를 options.
activations의 복제본으로 둡니다.
-
그렇지 않으면:
-
desc를 새
MLOperandDescriptor로 둡니다. -
그래프 연결을 구성합니다:
-
output0을 MLOperand를 생성한 결과로 두며 this와 desc가 주어집니다.
-
output1을 MLOperand를 생성한 결과로 두며 this와 desc가 주어집니다.
-
output을 목록 « output0, output1 »로 둡니다.
-
operator를 weight, recurrentWeight, hiddenState, cellState, hiddenSize 및 options가 주어진 "lstmCell" 연산의 연산자로 둡니다.
-
output0.
[[operator]]및 output1.[[operator]]를 operator로 설정합니다. -
operator의 입력을 input, weight, recurrentWeight, hiddenState, 그리고 cellState로 설정합니다.
-
options.
recurrentBias가 존재하면 이를 operator의 입력에 추가합니다. -
options.
peepholeWeight가 존재하면 이를 operator의 입력에 추가합니다. -
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
weight 레이아웃이 기본 "iofg"
레이아웃이고, input/forget/output gate와
cell gate/출력 은닉 상태를 위한 셀 상태 필터의 활성화 함수가 각각 sigmoid()
및 tanh()
인 경우 이 연산의 동작은 다른 연산을 사용하여 다음과 같이 일반적으로 에뮬레이션할 수 있지만,
사용자 에이전트에는 일반적으로 더 효율적인 구현이 있습니다. 기반 플랫폼이
연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로 사용할 수 있습니다.
function lstmCell( builder, input, weight, recurrentWeight, hiddenState, cellState, hiddenSize, options) { const zero= builder. constant( input. dataType, 0 ); const inputSize= input. shape[ 1 ]; // 입력 gate (i) let i= builder. sigmoid( builder. add( builder. mul( cellState, ( options. peepholeWeight? builder. slice( options. peepholeWeight, [ 0 ], [ hiddenSize]) : zero)), builder. add( builder. add( ( options. bias? builder. slice( options. bias, [ 0 ], [ hiddenSize]) : zero), ( options. recurrentBias? builder. slice( options. recurrentBias, [ 0 ], [ hiddenSize]) : zero)), builder. add( builder. matmul( input, builder. transpose( builder. slice( weight, [ 0 , 0 ], [ hiddenSize, inputSize]))), builder. matmul( hiddenState, builder. transpose( builder. slice( recurrentWeight, [ 0 , 0 ], [ hiddenSize, hiddenSize]))))))); // 망각 gate (f) let f= builder. sigmoid( builder. add( builder. mul( cellState, ( options. peepholeWeight? builder. slice( options. peepholeWeight, [ 2 * hiddenSize], [ hiddenSize]) : zero)), builder. add( builder. add( ( options. bias? builder. slice( options. bias, [ 2 * hiddenSize], [ hiddenSize]) : zero), ( options. recurrentBias? builder. slice( options. recurrentBias, [ 2 * hiddenSize], [ hiddenSize]) : zero)), builder. add( builder. matmul( input, builder. transpose( builder. slice( weight, [ 2 * hiddenSize, 0 ], [ hiddenSize, inputSize]))), builder. matmul( hiddenState, builder. transpose( builder. slice( recurrentWeight, [ 2 * hiddenSize, 0 ], [ hiddenSize, hiddenSize]))))))); // 셀 gate (g) let g= builder. tanh( builder. add( builder. add( ( options. bias? builder. slice( options. bias, [ 3 * hiddenSize], [ hiddenSize]) : zero), ( options. recurrentBias? builder. slice( options. recurrentBias, [ 3 * hiddenSize], [ hiddenSize]) : zero)), builder. add( builder. matmul( input, builder. transpose( builder. slice( weight, [ 3 * hiddenSize, 0 ], [ hiddenSize, inputSize]))), builder. matmul( hiddenState, builder. transpose( builder. slice( recurrentWeight, [ 3 * hiddenSize, 0 ], [ hiddenSize, hiddenSize])))))); // 출력 gate (o) let o= builder. sigmoid( builder. add( builder. mul( cellState, ( options. peepholeWeight? builder. slice( options. peepholeWeight, [ hiddenSize], [ hiddenSize]) : zero)), builder. add( builder. add( ( options. bias? builder. slice( options. bias, [ hiddenSize], [ hiddenSize]) : zero), ( options. recurrentBias? builder. slice( options. recurrentBias, [ hiddenSize], [ hiddenSize]) : zero)), builder. add( builder. matmul( input, builder. transpose( builder. slice( weight, [ hiddenSize, 0 ], [ hiddenSize, inputSize]))), builder. matmul( hiddenState, builder. transpose( builder. slice( recurrentWeight, [ hiddenSize, 0 ], [ hiddenSize, hiddenSize]))))))); // 출력 셀 상태 (ct) let ct= builder. add( builder. mul( f, cellState), builder. mul( i, g)); // 출력 은닉 상태 (ht) let ht= builder. mul( o, builder. tanh( ct)); return [ ht, ct]; }
8.9.35. matmul
두 입력 텐서의 행렬 곱을 계산합니다.partial interface MLGraphBuilder {MLOperand matmul (MLOperand a ,MLOperand b ,optional MLOperatorOptions options = {}); };partial dictionary MLOpSupportLimits {MLBinarySupportLimits matmul ; };
-
a:MLOperand입니다. 최소 2차원인 첫 번째 입력 텐서입니다. -
b:MLOperand입니다. 최소 2차원인 두 번째 입력 텐서입니다. -
options:MLOperatorOptions입니다. 연산의 선택적 매개변수를 지정합니다.
반환: MLOperand입니다.
두 입력 텐서의 행렬
곱을 포함하는 출력 텐서입니다.
-
a또는b중 하나가N차원이고N > 2이면 마지막 두 인덱스에 대응하는 차원을 가진 행렬 스택으로 취급합니다. 행렬 곱셈은 브로드캐스트되며 [numpy-broadcasting-rule]을 따릅니다.a와b의 shape은 마지막 두 차원을 제외하고 양방향 브로드캐스트 가능해야 합니다. 출력은 입력 텐서의 최대 랭크를 랭크로 갖는N차원 텐서입니다. 출력 텐서의 마지막 두 차원을 제외한 각 차원에 대해 그 크기는 입력 텐서에서 해당 차원을 따른 최대 크기입니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
a
| "float32",
"float16"
| "float32",
"float16"
| 2에서 N까지 | 2에서 5까지 |
b
| 동일한 유형 a
| "float32",
"float16"
| 2에서 N까지 | 2에서 5까지 |
| 출력 | 동일한 유형 a
| "float32",
"float16"
| 2에서 N까지 | 2에서 5까지 |
MLOpSupportLimits
에는 matmul()에
대해 다음 멤버가 있습니다:
matmul, 유형은 MLBinarySupportLimits-
matmul()연산자의 지원 제한입니다.
matmul(a, b, options)
메서드 단계는 다음과 같습니다:
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 a 및 b 중 하나가 false를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
a 또는 b 중 하나의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름) 예외를 발생시킵니다.
TypeError입니다. -
출력 shape을 계산합니다:
-
rankA를 a의 랭크로 둡니다.
-
rankB를 b의 랭크로 둡니다.
-
colsA를 shapeA[rankA - 1]로 둡니다.
-
rowsA를 shapeA[rankA - 2]로 둡니다.
-
colsB를 shapeB[rankB - 1]로 둡니다.
-
rowsB를 shapeB[rankB - 2]로 둡니다.
-
outputShape을 batchShapeA와 batchShapeB를 양방향 브로드캐스트한 결과로 둡니다. 실패를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
추가합니다 « rowsA, colsB »를 outputShape에.
-
desc를 a의 dataType과 outputShape이 주어진 상태에서 MLOperandDescriptor를 생성한 결과로 둡니다.
-
그래프 연결을 구성합니다:
-
output을 MLOperand를 생성한 결과로 두며 this와 desc가 주어집니다.
-
operator를 options가 주어진 "matmul" 연산의 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 a와 b로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
8.9.36. pad
가장자리에 상수 또는 미러링된 값을 사용하여 텐서를 확장합니다.enum {MLPaddingMode ,"constant" ,"edge" };"reflection" dictionary :MLPadOptions MLOperatorOptions {MLPaddingMode mode = "constant";MLNumber value = 0; };partial interface MLGraphBuilder {MLOperand pad (MLOperand input ,sequence <[EnforceRange ]unsigned long >beginningPadding ,sequence <[EnforceRange ]unsigned long >endingPadding ,optional MLPadOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits pad ; };
MLPadOptions
에는 다음 멤버가 있습니다:
mode, 유형은 MLPaddingMode이며 기본값은"constant"-
텐서를 패딩하는 여러 방식입니다.
value, 유형은 MLNumber이며 기본값은0-
mode가"constant"로 설정된 경우의 패딩 값입니다.
-
input:MLOperand입니다. 입력 텐서입니다. -
beginningPadding: sequence<unsigned long>. 각 입력 차원의 시작 부분에 추가할 패딩 값의 개수이며, 길이는 N이고 여기서 N은 입력 텐서의 랭크입니다.input의 각 차원 d에 대해beginningPadding[d]는 해당 차원의 내용 앞에 추가할 값의 개수를 나타냅니다. -
endingPadding: sequence<unsigned long>. 각 입력 차원의 끝부분에 추가할 패딩 값의 개수이며, 길이는 N이고 여기서 N은 입력 텐서의 랭크입니다.input의 각 차원 d에 대해endingPadding[d]는 해당 차원의 내용 뒤에 추가할 값의 개수를 나타냅니다. -
options: 선택적MLPadOptions입니다. 연산의 선택적 매개변수입니다.
반환: MLOperand입니다.
패딩된 출력 텐서입니다. 출력 텐서의 각 차원은 다음과 같이 계산할 수 있습니다:
output size = beginning padding + input size + ending padding
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
input
| 모두 | "float32",
"float16"
| N | 0에서 5까지 |
| 출력 | 동일한 유형 input
| "float32",
"float16"
| 동일한 랭크 input
| 0에서 5까지 |
MLOpSupportLimits
에는 pad()에
대해 다음 멤버가 있습니다:
pad, 유형은 MLSingleInputSupportLimits-
pad()연산자의 지원 제한입니다.
pad(input, beginningPadding, endingPadding, options)
메서드 단계는 다음과 같습니다:
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input이 false를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
beginningPadding의 크기와 endingPadding의 크기가 둘 다 input의 랭크와 같지 않으면 예외를 발생시킵니다.
TypeError입니다. -
desc를 input.
[[descriptor]]의 복사본으로 둡니다. -
outputShape을 input의 shape의 복사본으로 둡니다.
-
각각 index에 대해 범위 0부터 outputShape의 랭크까지, 상한 제외:
-
options.
mode에 따라 분기합니다:"constant"-
아무 작업도 하지 않습니다.
"edge"-
아무 작업도 하지 않습니다.
"reflection"
-
outputShape[index]에 다음 값을 더합니다: beginningPadding[index].
-
outputShape[index]에 다음 값을 더합니다: endingPadding[index].
-
-
outputShape의 항목 중 하나라도 유효한 차원이 아니면 예외를 발생시킵니다.
TypeError입니다. -
options.
value를 options.value를 input의 캐스트한 dataType 결과로 설정합니다. -
desc.
shape을 outputShape으로 설정합니다. -
그래프 연결을 구성합니다:
-
output을 MLOperand를 생성한 결과로 두며 this와 desc가 주어집니다.
-
operator를 beginningPadding, endingPadding 및 options가 주어진 "padding" 연산의 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
constant, edge 및 reflection 패딩의 예:
// 입력: [[1,2,3], [4,5,6]] const input= builder. constant( { dataType: 'float32' , shape: [ 2 , 3 ]}, new Float32Array([ 1 , 2 , 3 , 4 , 5 , 6 ])); const beginningPadding= [ 1 , 2 ]; const endingPadding= [ 1 , 2 ]; // "constant" 패딩: // [[0,0,0,0,0,0,0], // [0,0,1,2,3,0,0], // [0,0,4,5,6,0,0], // [0,0,0,0,0,0,0]] builder. pad( input, beginningPadding, endingPadding); // "edge" 패딩: // [[1,1,1,2,3,3,3], // [1,1,1,2,3,3,3], // [4,4,4,5,6,6,6], // [4,4,4,5,6,6,6]] builder. pad( input, beginningPadding, endingPadding, { mode: 'edge' }); // "reflection" 패딩: // [[6,5,4,5,6,5,4], // [3,2,1,2,3,2,1], // [6,5,4,5,6,5,4], // [3,2,1,2,3,2,1]] builder. pad( input, beginningPadding, endingPadding, { mode: 'reflection' });
8.9.37. 풀링 연산
입력 텐서 위를 이동하는 윈도우 내의 모든 요소에 대해 풀링 연산을 계산합니다.enum {MLRoundingType ,"floor" };"ceil" dictionary :MLPool2dOptions MLOperatorOptions {sequence <[EnforceRange ]unsigned long >windowDimensions ;sequence <[EnforceRange ]unsigned long >padding ;sequence <[EnforceRange ]unsigned long >strides ;sequence <[EnforceRange ]unsigned long >dilations ;MLInputOperandLayout layout = "nchw";MLRoundingType outputShapeRounding = "floor";sequence <[EnforceRange ]unsigned long >outputSizes ; };partial interface MLGraphBuilder {MLOperand averagePool2d (MLOperand input ,optional MLPool2dOptions options = {});MLOperand l2Pool2d (MLOperand input ,optional MLPool2dOptions options = {});MLOperand maxPool2d (MLOperand input ,optional MLPool2dOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits averagePool2d ;MLSingleInputSupportLimits l2Pool2d ;MLSingleInputSupportLimits maxPool2d ; };
MLPool2dOptions
에는 다음 멤버가 있습니다:
windowDimensions, 유형은sequence<[EnforceRange] unsigned long>-
길이가 2인 목록입니다: [windowHeight, windowWidth]. 슬라이딩 윈도우의 차원을 지정합니다. 윈도우 차원의 기본값은 입력 shape의 높이 및 너비 차원입니다.
padding, 유형은sequence<[EnforceRange] unsigned long>-
길이가 4인 목록입니다: [beginningHeight, endingHeight, beginningWidth, endingWidth]. 컨볼루션 입력의 각 공간 차원 시작과 끝에 추가되는 행 및 열을 지정합니다. 기본값은 [0,0,0,0]입니다.
strides, 유형은sequence<[EnforceRange] unsigned long>-
길이가 2인 목록입니다: [strideHeight, strideWidth]. 컨볼루션 입력의 각 공간 차원에 대한 슬라이딩 윈도우의 stride를 지정합니다. 기본값은 [1,1]입니다.
dilations, 유형은sequence<[EnforceRange] unsigned long>-
길이가 2인 목록입니다: [dilationHeight, dilationWidth]. 컨볼루션 필터(커널)에 적용되는 각 공간 차원의 dilation factor를 지정합니다. 기본값은 [1,1]입니다.
layout, 유형은 MLInputOperandLayout이며 기본값은"nchw"-
입력 및 출력 텐서의 레이아웃 형식을 다음과 같이 지정합니다:
outputShapeRounding, 유형은 MLRoundingType이며 기본값은"floor"-
전체 또는 부분 윈도우 결과를 원하는지에 따라 출력 shape을 계산하는 데 사용하는 반올림 함수입니다.
outputSizes, 유형은sequence<[EnforceRange] unsigned long>-
길이가 2인 목록입니다: [outputHeight, outputWidth] 출력 텐서의 두 공간 차원 크기를 지정합니다. 출력 크기를 명시적으로 지정하면
outputShapeRounding은 무시됩니다. 지정하지 않으면 출력 크기가 자동으로 계산됩니다.
-
input:MLOperand입니다. 입력 4차원 텐서입니다. 논리적 shape은layout값에 따라 해석됩니다. -
options: 선택적MLPool2dOptions입니다. 연산의 선택적 매개변수입니다.
반환: MLOperand입니다.
축소
결과를 포함하는 출력 4차원 텐서입니다. 논리적 shape은
layout
값에 따라 해석됩니다.
더 구체적으로 outputShapeRounding
이 "floor"이면,
출력 텐서의 단일 차원에 대한 공간 차원은 다음과 같이 계산할 수 있습니다:
output size = floor(1 + (input size - filter size + beginning padding + ending padding) / stride)
또는 outputShapeRounding
이 "ceil"이면:
output size = ceil(1 + (input size - filter size + beginning padding + ending padding) / stride)
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
input
| "float32",
"float16"
| "float32",
"float16"
| 4 | 4 |
| 출력 | 동일한 유형 input
| "float32",
"float16"
| 4 | 4 |
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
input
| 모두 | "float32",
"float16"
| 4 | 4 |
| 출력 | 동일한 유형 input
| "float32",
"float16"
| 4 | 4 |
MLOpSupportLimits
에는 풀링 연산에 대해 다음 멤버가 있습니다:
averagePool2d, 유형은 MLSingleInputSupportLimits-
averagePool2d()연산자의 지원 제한입니다. l2Pool2d, 유형은 MLSingleInputSupportLimits-
l2Pool2d()연산자의 지원 제한입니다. maxPool2d, 유형은 MLSingleInputSupportLimits-
maxPool2d()연산자의 지원 제한입니다.
// '전역' max 풀링 builder. maxPool2d( input);
풀링 연산을 생성하려면 문자열
op, MLOperand
input, MLPool2dOptions
options, 그리고 선택적 목록 allowedDataTypes가 주어졌을 때 다음 단계를 실행합니다:
-
단언: op는 "averagePool2d", "l2Pool2d", "maxPool2d" 중 하나입니다.
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input이 false를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
allowedDataTypes가 주어지고 input의 dataType을 포함하지 않으면 예외를 발생시킵니다.
TypeError입니다. -
options.
layout에 따라 분기합니다: -
options.
windowDimensions이 존재하지 않으면 options.windowDimensions을 « inputHeight, inputWidth »로 설정합니다. -
options.
windowDimensions의 크기가 2가 아니면 예외를 발생시킵니다.TypeError입니다. -
options.
windowDimensions의 항목 중 하나라도 0이면 예외를 발생시킵니다.TypeError입니다. -
options.
outputSizes가 존재하거나 options.padding이 존재하지 않으면 options.padding을 목록 « 0, 0, 0, 0 »로 설정합니다. -
options.
strides가 존재하지 않으면 options.strides를 목록 « 1, 1 »로 설정합니다. -
options.
outputSizes가 존재하면: -
options.
dilations가 존재하지 않으면 options.dilations를 목록 « 1, 1 »로 설정합니다. -
desc를 input.
[[descriptor]]의 복사본으로 둡니다. -
출력 shape을 계산합니다:
-
« windowHeight, windowWidth »를 options.
windowDimensions으로 둡니다. -
« calculatedOutputHeight, calculatedOutputWidth »를 inputHeight, inputWidth, windowHeight, windowWidth, options.
padding, options.strides, 그리고 options.dilations가 주어진 상태에서 conv2d 출력 크기를 계산한 결과로 둡니다. -
options.
outputSizes가 존재하면:-
« outputHeight, outputWidth »를 options.
outputSizes로 둡니다. -
outputHeight가 floor( calculatedOutputHeight )와 같고 outputWidth가 floor( calculatedOutputWidth )와 같은 것도 아니며, outputHeight가 ceil( calculatedOutputHeight )과 같고 outputWidth가 ceil( calculatedOutputWidth )과 같은 것도 아니면 예외를 발생시킵니다.
TypeError입니다.
-
-
그렇지 않으면:
-
« outputHeight, outputWidth »를 « calculatedOutputHeight, calculatedOutputWidth »로 둡니다.
-
options.
outputShapeRounding에 따라 분기합니다:
-
-
outputHeight 또는 outputWidth 중 하나가 유효한 차원이 아니면 예외를 발생시킵니다.
TypeError입니다. -
options.
layout에 따라 분기합니다: -
desc.
shape을 outputShape으로 설정합니다.
-
-
그래프 연결을 구성합니다:
-
output을 MLOperand를 생성한 결과로 두며 this와 desc가 주어집니다.
-
operator를 options가 주어진 op 연산의 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
다음 풀링 알고리즘을 지원합니다.
averagePool2d(input, options)
메서드 단계는 다음과 같습니다:
-
output을 "averagePool2d", input, options, 그리고 «
"float32","float16"»가 주어진 상태에서 풀링 연산을 생성한 결과로 둡니다. -
output을 반환합니다.
l2Pool2d(input, options)
메서드 단계는 다음과 같습니다:
-
output을 "l2Pool2d", input, options, 그리고 «
"float32","float16"»가 주어진 상태에서 풀링 연산을 생성한 결과로 둡니다. -
output을 반환합니다.
maxPool2d(input, options)
메서드 단계는 다음과 같습니다:
-
output을 "maxPool2d", input 및 options가 주어진 상태에서 풀링 연산을 생성한 결과로 둡니다.
-
output을 반환합니다.
8.9.37.1. averagePool2d
feature map의 패치에 대한 평균값을 계산하고 이를 사용하여 풀링된 feature map을 생성합니다. 자세한 내용은 § 8.9.37 풀링 연산을 참조하십시오.8.9.37.2. l2Pool2d
입력 feature map의 영역에 L2 norm 함수를 적용합니다. L2 norm은 해당 요소 제곱합의 제곱근입니다. 자세한 내용은 § 8.9.37 풀링 연산에서 확인할 수 있습니다.8.9.37.3. maxPool2d
feature map의 패치에 대한 최댓값을 계산하고 이를 사용하여 풀링된 feature map을 생성합니다. 자세한 내용은 § 8.9.37 풀링 연산을 참조하십시오.8.9.38. prelu
입력 텐서에 요소별로 정류 선형 함수의 매개변수화된 버전(Parametric ReLU)을 계산합니다. Parametric ReLU는 0.01과 같은 스칼라 slope를 갖는 대신 slope(누설 계수)를 이 연산의 모델 학습 단계에서 학습되는 매개변수로 만드는 leaky ReLU 유형입니다. 계산은max(0, x) + slope * min(0, x) 식을 따릅니다.
연산은 브로드캐스트되며 [numpy-broadcasting-rule]을 따릅니다. 입력 텐서는 양방향 브로드캐스트 가능해야 합니다. 출력 텐서의 랭크는 입력 텐서의 최대 랭크입니다. 출력 텐서의 각 차원에 대해 그 크기는 입력 텐서에서 해당 차원을 따른 최대 크기입니다.
partial interface MLGraphBuilder {MLOperand prelu (MLOperand input ,MLOperand slope ,optional MLOperatorOptions options = {}); };dictionary {MLPreluSupportLimits MLTensorLimits input ;MLTensorLimits slope ;MLTensorLimits output ; };partial dictionary MLOpSupportLimits {MLPreluSupportLimits prelu ; };
-
input:MLOperand입니다. 입력 텐서입니다. -
slope:MLOperand입니다. slope 텐서입니다. 그 shape은 양방향 브로드캐스트 가능해야 하며input의 shape에 대해 적용됩니다. -
options:MLOperatorOptions입니다. 연산의 선택적 매개변수를 지정합니다.
반환:
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
input
| "float32",
"float16",
"int64",
"int32",
"int8"
| "float32",
"float16"
| N | 0에서 5까지 |
slope
| 동일한 유형 input
| "float32",
"float16"
| N | 0에서 5까지 |
| 출력 | 동일한 유형 input
| "float32",
"float16"
| N | 0에서 5까지 |
MLPreluSupportLimits
에는 다음 멤버가 있습니다:
input, 유형은 MLTensorLimits-
MLTensorLimits입력 피연산자에 대한 것입니다. slope, 유형은 MLTensorLimits-
MLTensorLimitsslope 피연산자에 대한 것입니다. output, 유형은 MLTensorLimits-
MLTensorLimits출력 피연산자에 대한 것입니다.
MLOpSupportLimits
에는 prelu()에
대해 다음 멤버가 있습니다:
prelu, 유형은 MLPreluSupportLimits-
prelu()연산자의 지원 제한입니다.
prelu(input, slope, options)
메서드 단계는 다음과 같습니다:
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input 및 slope 중 하나가 false를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
input 또는 slope 중 하나의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름) 예외를 발생시킵니다.
TypeError입니다. -
outputShape을 slope의 shape과 input의 shape을 양방향 브로드캐스트한 결과로 둡니다.
-
descriptor를 input의 dataType과 outputShape이 주어진 상태에서 MLOperandDescriptor를 생성한 결과로 둡니다.
-
그래프 연결을 구성합니다:
-
output을 MLOperand를 생성한 결과로 두며 this와 descriptor가 주어집니다.
-
operator를 slope와 options가 주어진 "prelu" 연산의 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input과 slope로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
이 연산의 동작은 다른 연산을 사용하여 일반적으로 에뮬레이션할 수 있으며 다음과 같습니다. 다만 사용자 에이전트에는 일반적으로 더 효율적인 구현이 있습니다. 기반 플랫폼이 연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로 사용할 수 있습니다.
function prelu( builder, input, slope) { return builder. add( builder. max( builder. constant( input. dataType, 0 ), input), builder. mul( slope, builder. min( builder. constant( input. dataType, 0 ), input))); }
8.9.39. 축소 연산
모든 차원을 따라 또는axes
배열 매개변수에 지정된 축을 따라 입력 텐서를 축소합니다. 지정된 각 축에 대해 해당 인덱스의 차원이 축소됩니다. 즉, 결과 텐서에는
해당 차원이 포함되지 않지만 keepDimensions
가 지정된 경우에는 포함됩니다. 결과 텐서의 값은 축소된 차원의 모든 입력 값을
매개변수로 받는 지정된 축소 함수를 사용하여 계산합니다.
dictionary :MLReduceOptions MLOperatorOptions {sequence <[EnforceRange ]unsigned long >axes ;boolean keepDimensions =false ; };partial interface MLGraphBuilder {MLOperand reduceL1 (MLOperand input ,optional MLReduceOptions options = {});MLOperand reduceL2 (MLOperand input ,optional MLReduceOptions options = {});MLOperand reduceLogSum (MLOperand input ,optional MLReduceOptions options = {});MLOperand reduceLogSumExp (MLOperand input ,optional MLReduceOptions options = {});MLOperand reduceMax (MLOperand input ,optional MLReduceOptions options = {});MLOperand reduceMean (MLOperand input ,optional MLReduceOptions options = {});MLOperand reduceMin (MLOperand input ,optional MLReduceOptions options = {});MLOperand reduceProduct (MLOperand input ,optional MLReduceOptions options = {});MLOperand reduceSum (MLOperand input ,optional MLReduceOptions options = {});MLOperand reduceSumSquare (MLOperand input ,optional MLReduceOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits reduceL1 ;MLSingleInputSupportLimits reduceL2 ;MLSingleInputSupportLimits reduceLogSum ;MLSingleInputSupportLimits reduceLogSumExp ;MLSingleInputSupportLimits reduceMax ;MLSingleInputSupportLimits reduceMean ;MLSingleInputSupportLimits reduceMin ;MLSingleInputSupportLimits reduceProduct ;MLSingleInputSupportLimits reduceSum ;MLSingleInputSupportLimits reduceSumSquare ; };
MLReduceOptions
에는 다음 멤버가 있습니다:
axes, 유형은sequence<[EnforceRange] unsigned long>-
축소할 차원이며, 입력 텐서의 어떤 값을 축소 함수에 사용할지도 지정합니다. 목록의 축은 입력 텐서의 랭크가 N일 때 [0, N-1] 범위에 있어야 합니다.
존재하지 않으면 모든 차원이 축소됩니다. 축소 함수의 입력 값은 입력 텐서의 모든 값입니다.
존재하고 비어 있지 않으면 축소 함수의 입력 값은 입력 텐서의 지정된 차원에 있는 모든 값입니다.
존재하고 비어 있으면 어떤 차원도 축소되지 않으며 출력 텐서의 shape은 입력 텐서의 shape과 같습니다. 축소 함수는 텐서의 각 값에 개별적으로 적용됩니다.
keepDimensions, 유형은 boolean이며 기본값은false-
true이면 출력은 입력과 동일한 랭크를 가지며 축소된 모든 차원의 크기를 1로 설정합니다.
-
input:MLOperand입니다. 입력 텐서입니다. -
options: 선택적MLReduceOptions입니다. 연산의 선택적 매개변수입니다.
반환: MLOperand입니다.
출력 N차원 텐서의 랭크는 0에서
input의
랭크까지의 범위이며 양 끝을 포함하고,
axes
및 keepDimensions에
따라 달라집니다.
입력 피연산자가 스칼라이면 축소 함수가 스칼라 값에 적용되며 출력도
스칼라입니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
input
| "float32",
"float16",
"int32",
"uint32",
"int64",
"uint64"
| "float32",
"float16",
"int32"
| N | 0에서 5까지 |
| 출력 | 동일한 유형 input
| "float32",
"float16",
"int32"
| N | 0에서 5까지 |
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
input
| "float32",
"float16"
| "float32",
"float16"
| N | 0에서 5까지 |
| 출력 | 동일한 유형 input
| "float32",
"float16"
| N | 0에서 5까지 |
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
input
| 모두 | "float32",
"float16",
"int32"
| N | 0에서 5까지 |
| 출력 | 동일한 유형 input
| "float32",
"float16",
"int32"
| N | 0에서 5까지 |
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
input
| "float32",
"float16",
"int32",
"uint32",
"int64",
"uint64"
| "float32",
"float16"
| N | 0에서 5까지 |
| 출력 | 동일한 유형 input
| "float32",
"float16"
| N | 0에서 5까지 |
MLOpSupportLimits
에는 축소 연산에 대해 다음 멤버가 있습니다:
reduceL1, 유형은 MLSingleInputSupportLimits-
reduceL1()연산자의 지원 제한입니다. reduceL2, 유형은 MLSingleInputSupportLimits-
reduceL2()연산자의 지원 제한입니다. reduceLogSum, 유형은 MLSingleInputSupportLimits-
reduceLogSum()연산자의 지원 제한입니다. reduceLogSumExp, 유형은 MLSingleInputSupportLimits-
reduceLogSumExp()연산자의 지원 제한입니다. reduceMax, 유형은 MLSingleInputSupportLimits-
reduceMax()연산자의 지원 제한입니다. reduceMean, 유형은 MLSingleInputSupportLimits-
reduceMean()연산자의 지원 제한입니다. reduceMin, 유형은 MLSingleInputSupportLimits-
reduceMin()연산자의 지원 제한입니다. reduceProduct, 유형은 MLSingleInputSupportLimits-
reduceProduct()연산자의 지원 제한입니다. reduceSum, 유형은 MLSingleInputSupportLimits-
reduceSum()연산자의 지원 제한입니다. reduceSumSquare, 유형은 MLSingleInputSupportLimits-
reduceSumSquare()연산자의 지원 제한입니다.
부호 없는 정수의 목록 inputShape, 선택적 부호 없는 정수의 목록 axes, 그리고 불리언 keepDimensions가 주어졌을 때 축소 출력 크기를 계산하려면 다음 단계를 수행합니다. 이 단계는 부호 없는 정수의 새 목록 또는 실패를 반환합니다.
축소 연산을 생성하려면 문자열
op, MLOperand
input, MLReduceOptions
options, 그리고 선택적 목록 allowedDataTypes가 주어졌을 때 다음 단계를 실행합니다:
-
단언: op는 "reduceL1", "reduceL2", "reduceLogSum", "reduceLogSumExp", "reduceMax", "reduceMean", "reduceMin", "reduceProduct", "reduceSum", "reduceSumSquare" 중 하나입니다.
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input이 false를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
allowedDataTypes가 주어지고 input의 dataType을 포함하지 않으면 예외를 발생시킵니다.
TypeError입니다. -
outputShape을 input의 shape, options.
axes(존재하는 경우), 그리고 options.keepDimensions가 주어진 상태에서 축소 출력 크기를 계산한 결과로 둡니다. 실패를 반환하면 예외를 발생시킵니다.TypeError입니다. -
desc를 input의 dataType과 outputShape이 주어진 상태에서 MLOperandDescriptor를 생성한 결과로 둡니다.
-
그래프 연결을 구성합니다:
-
output을 MLOperand를 생성한 결과로 두며, this와 desc가 주어집니다.
-
operator를 options가 주어진 op 연산에 대한 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
다음 축소 알고리즘을 지원합니다.
reduceL1(input, options)
메서드 단계는 다음과 같습니다:
reduceL2(input, options)
메서드 단계는 다음과 같습니다:
-
output을 축소 연산을 생성한 결과로 두며 "reduceL2", input, options, 그리고 «
"float32","float16"»가 주어집니다. -
output을 반환합니다.
reduceLogSum(input, options)
메서드 단계는 다음과 같습니다:
-
output을 축소 연산을 생성한 결과로 두며 "reduceLogSum", input, options, 그리고 «
"float32","float16"»가 주어집니다. -
output을 반환합니다.
reduceLogSumExp(input, options)
메서드 단계는 다음과 같습니다:
-
output을 축소 연산을 생성한 결과로 두며 "reduceLogSumExp", input, options, 그리고 «
"float32","float16"»가 주어집니다. -
output을 반환합니다.
reduceMax(input, options)
메서드 단계는 다음과 같습니다:
-
output을 축소 연산을 생성한 결과로 두며 "reduceMax", input 및 options가 주어집니다.
-
output을 반환합니다.
reduceMean(input, options)
메서드 단계는 다음과 같습니다:
-
output을 축소 연산을 생성한 결과로 두며 "reduceMean", input, options, 그리고 «
"float32","float16"»가 주어집니다. -
output을 반환합니다.
reduceMin(input, options)
메서드 단계는 다음과 같습니다:
-
output을 축소 연산을 생성한 결과로 두며 "reduceMin", input 및 options가 주어집니다.
-
output을 반환합니다.
reduceProduct(input, options)
메서드 단계는 다음과 같습니다:
reduceSum(input, options)
메서드 단계는 다음과 같습니다:
여러 축소 연산의 동작은 다른 연산을 사용하여 다음과 같이 일반적으로 에뮬레이션할 수 있지만 사용자 에이전트에는 일반적으로 더 효율적인 구현이 있습니다. 기반 플랫폼이 연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로 사용할 수 있습니다.
function reduceLogSum( builder, input, options) { return builder. log( builder. reduceSum( input, options)); } function reduceLogSumExp( builder, input, options) { return builder. log( builder. reduceSum( builder. exp( input), options)); } function reduceSumSquare( builder, input, options) { return builder. reduceSum( builder. pow( input, 2 ), options); }
keepDimensions
와 같은 옵션을 직접 지원하지 않습니다. 이는 기반 텐서 데이터에는 영향을 주지 않고 shape에만 영향을 줍니다. 예를 들어 입력 shape이
[2, 3, 4]이고 축이 1이며 keepDimensions
가 true이면 예상되는 출력 shape은 [2, 1 ,4]입니다. 기반 플랫폼이 축소된
차원을 절대 유지하지 않는 경우 출력 shape은 [2, 4]가 됩니다. 구현은 no-op
reshape를 [2, 1, 4]로 도입할 수 있습니다. 마찬가지로 keepDimensions
가 false이지만 기반 플랫폼이 항상 축소된 차원을 유지하는 경우에도 비슷한 no-op reshape를 도입할 수 있습니다.
8.9.40. relu
입력 텐서의 정류 선형 함수를 계산합니다.partial interface MLGraphBuilder {MLOperand relu (MLOperand input ,optional MLOperatorOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits relu ; };
-
input:MLOperand입니다. 입력 텐서입니다. -
options:MLOperatorOptions입니다. 연산의 선택적 매개변수를 지정합니다.
반환:
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
input
| "float32",
"float16",
"int64",
"int32",
"int8"
| "float32",
"float16"
| N | 0에서 5까지 |
| 출력 | 동일한 유형 input
| "float32",
"float16"
| 동일한 랭크 input
| 0에서 5까지 |
MLOpSupportLimits
에는 relu()에
대해 다음 멤버가 있습니다:
relu, 유형은 MLSingleInputSupportLimits-
relu()연산자의 지원 제한입니다.
relu(input, options) 메서드
단계는 다음과 같습니다:
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input이 false를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
input의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름) 예외를 발생시킵니다.
TypeError입니다. -
그래프 연결을 구성합니다:
-
output을 input이 주어진 상태에서 MLOperand를 복사한 결과로 둡니다.
-
operator를 options가 주어진 "relu" 연산의 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
이 연산의 동작은 다른 연산을 사용하여 일반적으로 에뮬레이션할 수 있으며 다음과 같습니다. 다만 사용자 에이전트에는 일반적으로 더 효율적인 구현이 있습니다. 기반 플랫폼이 연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로 사용할 수 있습니다.
function relu( builder, input) { return builder. max( builder. constant( input. dataType, 0 ), input); }
8.9.41. resample2d
축과 스케일링 factor에 따라 소스에서 대상 차원으로 텐서 값을 리샘플링합니다.enum {MLInterpolationMode "nearest-neighbor" ,"linear" };dictionary :MLResample2dOptions MLOperatorOptions {MLInterpolationMode mode = "nearest-neighbor";sequence <float >scales ;sequence <[EnforceRange ]unsigned long >sizes ;sequence <[EnforceRange ]unsigned long >axes ; };partial interface MLGraphBuilder {MLOperand resample2d (MLOperand input ,optional MLResample2dOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits resample2d ; };
-
input:MLOperand입니다. 입력 4차원 텐서입니다. -
options: 선택적MLResample2dOptions입니다. 연산의 선택적 매개변수입니다.
반환: MLOperand입니다.
출력 4차원 텐서입니다.
MLResample2dOptions
에는 다음 멤버가 있습니다:
mode, 유형은 MLInterpolationMode이며 기본값은"nearest-neighbor"-
출력 텐서 값을 채우는 데 사용하는 보간 알고리즘입니다.
두 알고리즘 모두 각 공간 축에 대해 계산되는 다음 입력으로 시작합니다(
axes기준). 여기서inputSize는input텐서의 shape으로 주어지고,outputSize는sizes또는scales로 주어지며,outputCoordinate는 계산 중인 출력 텐서의 요소를 식별합니다.scale = outputSize / inputSize unclampedCoordinate = (outputCoordinate + 0.5) / scale - 0.5 inputCoordinate = clamp(unclampedCoordinate, 0, inputSize - 1)
출력 텐서의 주어진outputCoordinate.x및outputCoordinate.y위치에 대해 위 수식은 유리수inputCoordinate.x및inputCoordinate.y를 제공합니다.nearest-neighbor-
위에서 계산한
inputCoordinate.x및inputCoordinate.y는 다음과 같이 출력 텐서 값을 계산하는 nearest-neighbor 샘플링 알고리즘의 입력으로 사용됩니다:x = ceil(inputCoordinate.x - 0.5) y = ceil(inputCoordinate.y - 0.5) output tensor value = input tensor value at (x, y)
linear-
위에서 계산한
inputCoordinate.x및inputCoordinate.y는 다음과 같이 출력 텐서 값을 계산하는 bilinear 샘플링 알고리즘의 입력으로 사용됩니다:x0 = floor(inputCoordinate.x) x1 = ceil(inputCoordinate.x) y0 = floor(inputCoordinate.y) y1 = ceil(inputCoordinate.y) vx0y0 = input tensor value at (x0, y0) vx1y0 = input tensor value at (x1, y0) vx0y1 = input tensor value at (x0, y1) vx1y1 = input tensor value at (x1, y1) tx = inputCoordinate.x - x0 ty = inputCoordinate.y - y0 vy0 = vx0y0 * (1 - tx) + vx1y0 * tx vy1 = vx0y1 * (1 - tx) + vx1y1 * tx output tensor value = vy0 * (1 - ty) + vy1 * ty
scales, 유형은 sequence<float>-
길이가 2인 목록입니다.
axes에서 각 입력 차원에 대한 스케일링 factor를 지정합니다: [scaleForFirstAxis, scaleForSecondAxis]. 기본값은 [1.0, 1.0]입니다. sizes, 유형은sequence<[EnforceRange] unsigned long>-
길이가 2인 목록입니다.
axes에서 각 입력 차원에 대한 대상 크기를 지정합니다: [sizeForFirstAxis, sizeForSecondAxis].sizes를 지정하면scales는 무시됩니다. 스케일링 factor 값이 입력의 대상 크기에서 도출되기 때문입니다. axes, 유형은sequence<[EnforceRange] unsigned long>-
길이가 2인 목록입니다. 보간 알고리즘을 적용할 입력 텐서의 두 차원을 지정합니다. 기본값은 [2, 3]입니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
input
| "float32",
"float16",
"uint8",
"int8"
| "float32",
"float16"
| 4 | 4 |
| 출력 | 동일한 유형 input
| "float32",
"float16"
| 4 | 4 |
MLOpSupportLimits
에는 resample2d()에
대해 다음 멤버가 있습니다:
resample2d, 유형은 MLSingleInputSupportLimits-
resample2d()연산자의 지원 제한입니다.
resample2d(input, options)
메서드 단계는 다음과 같습니다:
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input이 false를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
input의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름) 예외를 발생시킵니다.
TypeError입니다. -
그렇지 않고 그 항목 중 하나라도 0보다 작거나 같거나 그 크기가 2가 아니면 예외를 발생시킵니다.
TypeError입니다. -
options.
sizes가 존재하고 그 크기가 2가 아니거나, 그 항목 중 하나라도 0이면 예외를 발생시킵니다.TypeError입니다. -
그렇지 않고 options.
axes에 중복 값이 포함되어 있거나 그 항목 중 하나라도 범위 0부터 input의 랭크까지에 없으면, 상한은 제외하며 예외를 발생시킵니다.TypeError입니다. -
출력 shape을 계산합니다:
-
inputDescriptor를 input.
[[descriptor]]로 둡니다. -
desc를 inputDescriptor.
dataType및 outputShape이 주어진 상태에서 MLOperandDescriptor를 생성한 결과로 둡니다.
-
-
그래프 연결을 구성합니다:
-
output을 MLOperand를 생성한 결과로 두며 this와 desc가 주어집니다.
-
operator를 options가 주어진 "resample2d" 연산의 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
linear
리샘플링을 수행하는 경우(공간 차원만 고려):
[ 0 1 2 3 ] [ 0 1 2 3 ] [ 12 13 14 15 ] [ 12 13 14 15 ]
[8, 8] 출력 텐서에서 예상되는 값은 다음과 같습니다:
[ 0 0.25 0.75 1.25 1.75 2.25 2.75 3 ] [ 0 0.25 0.75 1.25 1.75 2.25 2.75 3 ] [ 0 0.25 0.75 1.25 1.75 2.25 2.75 3 ] [ 3 3.25 3.75 4.25 4.75 5.25 5.75 6 ] [ 9 9.25 9.75 10.25 10.75 11.25 11.75 12 ] [ 12 12.25 12.75 13.25 13.75 14.25 14.75 15 ] [ 12 12.25 12.75 13.25 13.75 14.25 14.75 15 ] [ 12 12.25 12.75 13.25 13.75 14.25 14.75 15 ]
이는 샘플링이 균등하게 분포되고 대칭적이며 이미지 미러링에 강하고 모서리 값이 정렬되는 유용한 특성을 갖습니다.
8.9.42. reshape
텐서의 shape을 새 shape으로 변경합니다. Reshape는 텐서의 내용을 복사하거나 변경하지 않습니다. 단지 후속 연산을 위해 텐서의 논리적 shape만 변경합니다.partial interface MLGraphBuilder {MLOperand reshape (MLOperand input ,sequence <[EnforceRange ]unsigned long >newShape ,optional MLOperatorOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits reshape ; };
-
input:MLOperand입니다. 입력 텐서입니다. -
newShape: sequence<unsigned long>. 출력 텐서의 shape입니다.newShape이 의미하는 요소 수는 입력 텐서의 요소 수와 같아야 합니다. -
options:MLOperatorOptions입니다. 연산의 선택적 매개변수를 지정합니다.
반환: MLOperand입니다.
출력 텐서입니다. 출력
텐서의 값은 입력 텐서의 값과 같습니다. 출력
텐서의 shape은 newShape로
지정합니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
input
| 모두 | "float32",
"float16",
"int32",
"int8",
"uint8"
| N | 0에서 5까지 |
| 출력 | 동일한 유형 input
| "float32",
"float16",
"int32",
"int8",
"uint8"
| N | 0에서 5까지 |
MLOpSupportLimits
에는 reshape()에
대해 다음 멤버가 있습니다:
reshape, 유형은 MLSingleInputSupportLimits-
reshape()연산자의 지원 제한입니다.
reshape(input, newShape, options)
메서드 단계는 다음과 같습니다:
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input이 false를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
newShape의 크기가 출력 텐서의 허용되는 랭크가 아니면(이 표에 따름) 예외를 발생시킵니다.
TypeError입니다. -
outputShape을
unsigned long의 빈 배열로 둡니다. -
inputElementCount를 input의 항목인 shape의 모든 항목의 곱으로 둡니다. 빈 차원은 inputElementCount가 1이 되게 합니다.
-
newShape의 모든 값의 곱이 inputElementCount와 같지 않으면 예외를 발생시킵니다.
TypeError입니다. -
desc를 input.
[[descriptor]]의 복사본으로 둡니다. -
desc.
shape을 newShape으로 설정합니다. -
그래프 연결을 구성합니다:
-
output을 MLOperand를 생성한 결과로 두며 this와 desc가 주어집니다.
-
operator를 options가 주어진 "reshape" 연산의 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
8.9.43. reverse
지정된 축을 따라 텐서를 반전합니다.dictionary :MLReverseOptions MLOperatorOptions {sequence <[EnforceRange ]unsigned long >axes ; };partial interface MLGraphBuilder {MLOperand reverse (MLOperand input ,optional MLReverseOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits reverse ; };
MLReverseOptions
에는 다음 멤버가 있습니다:
axes, 유형은sequence<[EnforceRange] unsigned long>-
반전할 입력 차원의 인덱스입니다. 이 멤버가 없으면 모든 차원이 반전되는 것으로 처리합니다. 명시적으로 빈 값으로 전달하면 어떤 차원도 반전하지 않습니다.
-
input:MLOperand입니다. 입력 텐서입니다. -
options:MLOperatorOptions입니다. 연산의 선택적 매개변수를 지정합니다.
반환:
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
input
| 모두 | "float32",
"float16",
"int32"
| N | 0에서 5까지 |
| 출력 | 동일한 유형 input
| "float32",
"float16",
"int32"
| 동일한 랭크 input
| 0에서 5까지 |
MLOpSupportLimits
에는 reverse()에
대해 다음 멤버가 있습니다:
reverse, 유형은 MLSingleInputSupportLimits-
reverse()연산자의 지원 제한입니다.
reverse(input, options)
메서드 단계는 다음과 같습니다:
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input이 false를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
input의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름) 예외를 발생시킵니다.
TypeError입니다. -
inputRank를 input의 랭크로 둡니다.
-
axes가 주어지지 않으면 axes를 범위 0부터 inputRank까지로 두며, 상한은 제외합니다.
-
그렇지 않고 axes에 중복 값이 포함되어 있거나 그 요소 중 하나라도 범위 0부터 inputRank까지에 없으면, 상한은 제외하며 실패를 반환합니다.
-
그래프 연결을 구성합니다:
-
output을 input이 주어진 상태에서 MLOperand를 복사한 결과로 둡니다.
-
operator를 "reverse" 연산과 options에 대한 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
8.9.44. scatterElements
인덱스에 따라 축을 따라 updates 텐서의 값을 입력 텐서 복사본 위에 분산합니다.dictionary :MLScatterOptions MLOperatorOptions { [EnforceRange ]unsigned long axis = 0; };partial interface MLGraphBuilder {MLOperand scatterElements (MLOperand input ,MLOperand indices ,MLOperand updates ,optional MLScatterOptions options = {}); };dictionary {MLScatterSupportLimits MLTensorLimits input ;MLTensorLimits indices ;MLTensorLimits updates ;MLTensorLimits output ; };partial dictionary MLOpSupportLimits {MLScatterSupportLimits scatterElements ; };
MLScatterOptions
에는 다음 멤버가 있습니다:
axis, 유형은 unsigned long이며 기본값은0-
분산된 값을 가져오는 축입니다. 그 값은 입력 텐서의 랭크가 N일 때 [0, N-1] 범위에 있어야 합니다.
-
input:MLOperand입니다. 출력을 초기화하는 입력 N차원 텐서입니다. -
indices:MLOperand입니다. 분산할 입력 값의 인덱스를 나타내는 N차원 텐서입니다. 값의 유형은"int32","uint32", 또는"int64"이어야 하며, options.axis로 인덱싱되는 입력 차원의 크기가 N일 때 -N(포함)에서 N(제외) 범위에 있어야 합니다. 음수 인덱스는 차원의 끝에서부터 인덱싱함을 의미합니다. -
updates:MLOperand입니다. 입력 위에서 대체할 새 값이며 indices와 동일한 shape을 가집니다. -
options: 선택적MLScatterOptions입니다. 연산의 선택적 매개변수입니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
input
| 모두 | "float32",
"float16",
"int32"
| 1에서 N까지 | 1에서 5까지 |
indices
| "int32",
"uint32",
"int64"
| "int32"
| 동일한 랭크 input
| 1에서 5까지 |
updates
| 동일한 유형 input
| "float32",
"float16",
"int32"
| 동일한 랭크 input
| 1에서 5까지 |
| 출력 | 동일한 유형 input
| "float32",
"float16",
"int32"
| 동일한 랭크 input
| 1에서 5까지 |
MLScatterSupportLimits
에는 다음 멤버가 있습니다:
input, 유형은 MLTensorLimits-
MLTensorLimits입력 피연산자에 대한 것입니다. indices, 유형은 MLTensorLimits-
MLTensorLimitsindices 피연산자에 대한 것입니다. updates, 유형은 MLTensorLimits-
MLTensorLimitsupdates 피연산자에 대한 것입니다. output, 유형은 MLTensorLimits-
MLTensorLimits출력 피연산자에 대한 것입니다.
MLOpSupportLimits
에는 scatterElements()에
대해 다음 멤버가 있습니다:
scatterElements, 유형은 MLScatterSupportLimits-
scatterElements()연산자의 지원 제한입니다.
indices
매개변수는 scatterElements()
에 대해 그래프가 빌드될 때 허용 범위로 clamp할 수 없습니다. 입력은 실행 시점까지 알 수 없기 때문입니다.
지정된 clamping 동작을 기반 플랫폼이 제공하지 않으면 구현은 컴파일된 그래프에 clamp()
를 도입할 수 있습니다.
마찬가지로 기반 플랫폼이 음수 인덱스를 지원하지 않으면 구현은
컴파일된 그래프에 연산을 도입하여 차원 끝에서부터의 음수 인덱스를 양수
인덱스로 변환할 수 있습니다.
scatterElements(input, indices, updates, options)
메서드 단계는 다음과 같습니다:
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input, indices 및 updates 중 하나가 false를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
indices의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름) 예외를 발생시킵니다.
TypeError입니다. -
updates의 dataType이 input의 dataType과 같지 않으면 예외를 발생시킵니다.
TypeError입니다. -
input, indices 또는 updates 중 하나의 랭크가 해당 허용되는 랭크가 아니면 예외를 발생시킵니다.
TypeError입니다. -
axis를 options.
axis로 둡니다. -
indicesShapeExpected를 input의 shape의 복사본으로 둡니다.
-
indicesShapeExpected[axis]를 indices의 shape[axis]로 설정합니다.
-
indices의 shape이 indicesShapeExpected와 같지 않으면 예외를 발생시킵니다.
TypeError입니다. -
updates의 shape이 indices의 같지 않은 shape이면 예외를 발생시킵니다.
TypeError입니다. -
그래프 연결을 구성합니다:
-
output을 input이 주어진 상태에서 MLOperand를 복사한 결과로 둡니다.
-
operator를 input, indices, updates, 그리고 options가 주어진 "scatterElements" 연산의 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input, indices, 그리고 updates로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
서로 다른 슬라이싱 방식에서 scatterElements가 동작하는 방식의 예입니다.
// shape이 [4,3]인 입력: // [[ 0, 1, 2], // [10, 11, 12], // [20, 21, 22], // [30, 31, 32]] // shape이 [2,3]인 indices: // [[3, 1, 1], // [2, 0, 3]] // shape이 [2,3]인 updates: // [[-1, -2, -3], // [-4, -5, -6]] // axis = 0 (기본값) // shape이 [4,3]인 출력: // [[ 0, -5, 2], // [10, -2, -3], // [-4, 21, 22], // [-1, 31, -6]] const input1= builder. constant( { dataType: 'float32' , shape: [ 4 , 3 ]}, new Float32Array([ 0 , 1 , 2 , 10 , 11 , 12 , 20 , 21 , 22 , 30 , 31 , 32 ])); const indices1= builder. constant( { dataType: 'uint32' , shape: [ 2 , 3 ]}, new Uint32Array([ 3 , 1 , 1 , 2 , 0 , 3 ])); const updates1= builder. constant( { dataType: 'float32' , shape: [ 2 , 3 ]}, new Uint32Array([ - 1 , - 2 , - 3 , - 4 , - 5 , - 6 ])); const output1= builder. scatterElements( input1, indices1, updates1); // shape이 [4,3]인 입력: // [[ 0, 1, 2], // [10, 11, 12], // [20, 21, 22], // [30, 31, 32]] // shape이 [4,1]인 indices: // [[2], // [1], // [0], // [2]], // shape이 [4,1]인 updates: // [[-1], // [-2], // [-3], // [-4]], // axis = 1 // shape이 [4,3]인 출력: // [[ 0, 1, -1], // [10, -2, 12], // [-3, 21, 22], // [30, 31, -4]] const indices2= builder. constant( { dataType: 'uint32' , shape: [ 4 , 1 ]}, new Uint32Array([ 2 , 1 , 0 , 2 ])); const updates2= builder. constant( { dataType: 'float32' , shape: [ 4 , 1 ]}, new Uint32Array([ - 1 , - 2 , - 3 , - 4 ])); const output2= builder. scatterElements( input1, indices2, updates2, { axis: 1 }); // shape이 [4,2,2]인 입력: // [[[ 0, 1], // [ 10, 11]], // [[100, 101], // [110, 111]], // [[200, 201], // [210, 211]], // [[300, 301], // [310, 311]],] // shape이 [1,2,2]인 indices: // [[[0, 2], // [1, 3]]], // shape이 [1,2,2]인 updates: // [[[-1, -2], // [-3, -4]]], // axis = 0 // shape이 [4,2,2]인 출력: // [[[ -1, 1], // [ 10, 11]], // [[100, 101], // [ -3, 111]], // [[200, -2], // [210, 211]], // [[300, 301], // [310, -4]],] const inputData3= new Float32Array( [ 0 , 1 , 10 , 11 , 100 , 101 , 110 , 111 , 200 , 201 , 210 , 211 , 300 , 301 , 310 , 311 ]); const input3= builder. constant({ dataType: 'float32' , shape: [ 4 , 2 , 2 ]}, inputData3); const indices3= builder. constant( { dataType: 'uint32' , shape: [ 1 , 2 , 2 ]}, new Uint32Array([ 0 , 2 , 1 , 3 ])); const updates3= builder. constant( { dataType: 'float32' , shape: [ 1 , 2 , 2 ]}, new Uint32Array([ - 1 , - 2 , - 3 , - 4 ])); const output3= builder. scatterElements( input3, indices3, updates3, { axis: 0 });
8.9.45. scatterND
인덱스에 따라 업데이트 텐서의 값 슬라이스를 입력 텐서 복사본 위에 분산합니다.partial interface MLGraphBuilder {MLOperand scatterND (MLOperand input ,MLOperand indices ,MLOperand updates ,optional MLOperatorOptions options = {}); };partial dictionary MLOpSupportLimits {MLScatterSupportLimits scatterND ; };
-
input:MLOperand입니다. 출력을 초기화하는 입력 N차원 텐서입니다. -
indices:MLOperand입니다. indices 배열은 출력 텐서에 대한 전체 좌표를 포함하며, 가장 오른쪽 차원은 좌표당 차원 수를 나타냅니다. 따라서 shape이 [10,1]인 indices 텐서는 단일 축 인덱스 10개를 포함하고, shape이 [4,3]이면 3차원 좌표의 인덱스 4개를 포함합니다. 값의 유형은"int32","uint32", 또는"int64"이어야 하며, 각각은 대응하는 출력 차원의 크기가 N일 때 -N(포함)부터 N(제외)까지의 범위에 있어야 합니다. 음수 인덱스는 대응하는 차원의 끝에서부터 인덱싱함을 의미합니다. -
updates:MLOperand입니다. 입력 위에서 대체할 새 값입니다. -
options: 선택적MLScatterOptions입니다. 연산의 선택적 매개변수입니다.
반환: MLOperand입니다.
출력 N차원 텐서의 랭크는 input의
랭크 + indices의
랭크 - indices의
shape[-1] - 1과 같습니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
input
| 모두 | "float32",
"float16",
"int32"
| 1에서 N까지 | 1에서 5까지 |
indices
| "int32",
"uint32",
"int64"
| "int32"
| 1에서 N까지 | 1에서 5까지 |
updates
| 동일한 유형 input
| "float32",
"float16",
"int32"
| N | 0에서 5까지 |
| 출력 | 동일한 유형 input
| "float32",
"float16",
"int32"
| 1에서 N까지 | 1에서 5까지 |
MLOpSupportLimits
에는 scatterND()에
대해 다음 멤버가 있습니다:
scatterND, 유형은 MLScatterSupportLimits-
scatterND()연산자의 지원 제한입니다.
indices
매개변수는 scatterND()
에 대해 그래프가 빌드될 때 허용 범위로 clamp할 수 없습니다. 입력은
실행 시점까지 알 수 없기 때문입니다. 지정된 clamping 동작을 기반 플랫폼이 제공하지 않으면 구현은 clamp()
를 컴파일된 그래프에 도입할 수 있습니다.
마찬가지로 기반 플랫폼이 음수 인덱스를 지원하지 않으면 구현은
컴파일된 그래프에 연산을 도입하여 차원 끝에서부터의 음수 인덱스를 양수
인덱스로 변환할 수 있습니다.
scatterND(input, indices, updates, options)
메서드 단계는 다음과 같습니다:
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input, indices 및 updates 중 하나가 false를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
indices의 dataType이 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름) 예외를 발생시킵니다.
TypeError입니다. -
updates의 dataType이 input의 dataType과 같지 않으면 예외를 발생시킵니다.
TypeError입니다. -
input, indices 또는 updates 중 하나의 랭크가 해당 허용되는 랭크가 아니면 예외를 발생시킵니다.
TypeError입니다. -
indicesShape을 indices의 shape으로 두고 indicesRank 를 indices의 랭크로 둡니다.
-
indexableSize를 indicesRank - 1로 둡니다.
-
coordinateSize를 indicesShape[indexableSize]로 둡니다.
-
expectedUpdatesShape을 빈 목록으로 둡니다.
-
각각 index에 대해 범위 0부터 indexableSize까지에서, 상한은 제외합니다:
-
추가합니다 indicesShape[index]를 expectedUpdatesShape에.
-
-
각각 index에 대해 범위 coordinateSize부터 inputRank까지에서, 상한은 제외합니다:
-
추가합니다 inputShape[index]를 expectedUpdatesShape에.
-
-
updates의 shape이 expectedUpdatesShape과 같지 않으면 예외를 발생시킵니다.
TypeError입니다. -
outputShape을 input의 shape의 복사본으로 둡니다.
-
outputDesc를 input의 dataType과 outputShape이 주어진 상태에서 MLOperandDescriptor를 생성한 결과로 둡니다.
-
그래프 연결을 구성합니다:
-
output을 outputDesc가 주어진 상태에서 MLOperand를 생성한 결과로 둡니다.
-
operator를 input, indices, updates, 그리고 options가 주어진 "scatterND" 연산의 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input, indices, 그리고 updates로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
서로 다른 슬라이싱 방식에서 scatterND가 동작하는 방식의 예입니다.
// shape이 [8]인 입력: // [0, 1, 2, 3, 4, 5, 6, 7] // shape이 [4, 1]인 indices: // [[4], // [3], // [1], // [7]] // shape이 [4]인 updates: // [-1, -2, -3, -4] // shape이 [8]인 출력: // [0, -3, 2, -2, -1, 5, 6, -4] const input1= builder. constant( { dataType: 'float32' , shape: [ 8 ]}, new Float32Array([ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 ])); const indices1= builder. constant( { dataType: 'uint32' , shape: [ 4 , 1 ]}, new Uint32Array([ 4 , 3 , 1 , 7 ])); const updates1= builder. constant( { dataType: 'uint32' , shape: [ 4 ]}, new Uint32Array([ - 1 , - 2 , - 3 , - 4 ])); const output1= builder. scatterND( input1, indices1, updates1); // shape이 [2,2]인 입력: // [[0, 1], // [2, 3]] // shape이 [2,2]인 indices: // [[0, 0], // [1, 1]] // shape이 [2]인 updates: // [-1, -2] // shape이 [2,2]인 출력: // [[-1, 1], <= -1이 출력 좌표 [0, 0]에 기록됨 // [ 2, -2]] <= -2가 출력 좌표 [1, 1]에 기록됨 const input2= builder. constant( { dataType: 'float32' , shape: [ 2 , 2 ]}, new Float32Array([ 0 , 1 , 2 , 3 ])); const indices2= builder. constant( { dataType: 'uint32' , shape: [ 2 , 2 ]}, new Uint32Array([ 0 , 0 , 1 , 1 ])); const updates2= builder. constant({ dataType: 'uint32' , shape: [ 2 ]}, new Uint32Array([ - 1 , - 2 ])); const output2= builder. scatterND( input2, indices2, updates2); // shape이 [3,2]인 입력: // [[0, 1], // [2, 3], // [4, 5]] // shape이 [2,1]인 indices: // [[2], // [0]] // shape이 [2,2]인 updates: // [[-1, -2], // [-3, -4]] // shape이 [3,2]인 출력: // [[-3 ,-4], <= [-3, -4]가 출력 좌표 [0, *]에 기록됨 // [ 2, 3], // [-1, -2]] <= [-1, -2]가 출력 좌표 [2, *]에 기록됨 const input3= builder. constant( { dataType: 'float32' , shape: [ 3 , 2 ]}, new Float32Array([ 0 , 1 , 2 , 3 , 4 , 5 ])); const indices3= builder. constant( { dataType: 'uint32' , shape: [ 2 , 1 ]}, new Uint32Array([ 1 , 0 ])); const updates3= builder. constant( { dataType: 'uint32' , shape: [ 2 , 2 ]}, new Uint32Array([ - 1 , - 2 , - 3 , 4 ])); const output3= builder. scatterND( input3, indices3, updates3); // shape이 [2,2,2]인 입력: // [[[0, 1], // [2, 3]], // [[4, 5], // [6, 7]]] // shape이 [2,2]인 indices: // [[0, 1], // [1, 0]] // shape이 [2,2]인 updates: // [[-1, -2], // [-3, -4]] // shape이 [2,2,2]인 출력: // [[[ 0, 1], // [-1, -2]], <= [-1, -2]가 출력 좌표 [0, 1, *]에 기록됨 // [[-3, -4], <= [-3, -4]가 출력 좌표 [1, 0, *]에 기록됨 // [ 6, 7]]] const input4= builder. constant( { dataType: 'float32' , shape: [ 2 , 2 , 2 ]}, new Float32Array([ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 ])); const indices4= builder. constant( { dataType: 'uint32' , shape: [ 2 , 2 ]}, new Uint32Array([ 0 , 1 , 1 , 0 ])); const updates4= builder. constant( { dataType: 'uint32' , shape: [ 2 , 2 ]}, new Uint32Array([ - 1 , - 2 , - 3 , 4 ])); const output4= builder. scatterND( input4, indices4, updates4);
8.9.46. sigmoid
입력 텐서의 시그모이드 함수를 계산합니다. 계산은1 / (exp(-x) + 1) 식을 따릅니다.
partial interface MLGraphBuilder {MLOperand sigmoid (MLOperand input ,optional MLOperatorOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits sigmoid ; };
-
input:MLOperand입니다. 입력 텐서입니다. -
options:MLOperatorOptions입니다. 연산의 선택적 매개변수를 지정합니다.
반환:
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
input
| "float32",
"float16"
| "float32",
"float16"
| N | 0에서 5까지 |
| 출력 | 동일한 유형 input
| "float32",
"float16"
| 동일한 랭크 input
| 0에서 5까지 |
MLOpSupportLimits
에는 sigmoid()에
대해 다음 멤버가 있습니다:
sigmoid, 유형은 MLSingleInputSupportLimits-
sigmoid()연산자의 지원 제한입니다.
sigmoid(input, options)
메서드 단계는 다음과 같습니다:
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input이 false를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
input의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름) 예외를 발생시킵니다.
TypeError입니다. -
그래프 연결을 구성합니다:
-
output을 input이 주어진 상태에서 MLOperand를 복사한 결과로 둡니다.
-
operator를 options가 주어진 "sigmoid" 연산의 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
이 연산의 동작은 다른 연산을 사용하여 일반적으로 에뮬레이션할 수 있으며 다음과 같습니다. 다만 사용자 에이전트에는 일반적으로 더 효율적인 구현이 있습니다. 기반 플랫폼이 연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로 사용할 수 있습니다.
function sigmoid( builder, input) { return builder. div( builder. constant( input. dataType, 1 ), builder. add( builder. exp( builder. neg( input)), builder. constant( input. dataType, 1 ))); }
8.9.47. slice
입력 텐서의 슬라이스를 생성합니다.dictionary :MLSliceOptions MLOperatorOptions {sequence <[EnforceRange ]unsigned long >strides ; };partial interface MLGraphBuilder {MLOperand slice (MLOperand input ,sequence <[EnforceRange ]unsigned long >starts ,sequence <[EnforceRange ]unsigned long >sizes ,optional MLSliceOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits slice ; };
MLSliceOptions
에는 다음 멤버가 있습니다:
strides, 유형은sequence<[EnforceRange] unsigned long>-
각 축을 따라 각 입력에서 건너뛸 stride입니다. strides 배열의 길이는 입력 텐서의 랭크와 같아야 합니다. 기본값은 모두 1로 구성되고 길이가 랭크인 배열입니다. 예: 3차원 텐서의 경우 [1,1,1]. Stride는 0보다 커야 합니다.
-
input:MLOperand입니다. 입력 텐서입니다. -
starts: sequence<unsigned long>. 각 입력 차원에서 슬라이스할 시작 인덱스이며, 길이는 N이고 여기서 N은 입력 텐서의 랭크입니다.input의 각 차원 d에 대해starts[d] 는 해당 차원에서 슬라이스할 시작 인덱스를 나타냅니다. 시작 인덱스는 해당 차원에서 [0, input size - 1] 범위에 있어야 합니다. -
sizes: sequence<unsigned long>. 각 입력 차원에서 슬라이스할 요소 수이며, 길이는 N이고 여기서 N은 입력 텐서의 랭크입니다.input의 각 차원 d에 대해sizes[d] 는 해당 차원에서 슬라이스할 요소 수를 나타냅니다. 크기는 0이면 안 되며 해당 차원에서starting index + size <= input size제약 조건을 충족해야 합니다. -
options:MLSliceOptions입니다. 연산의 선택적 매개변수를 지정합니다.
반환: MLOperand입니다.
입력 텐서와 동일한 랭크를 가지며 각 차원에서 지정된
시작 및 끝 인덱스로 텐서 값이 잘린 출력 텐서입니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
input
| 모두 | "float32",
"float16",
"int32",
"int8",
"uint8"
| N | 0에서 5까지 |
| 출력 | 동일한 유형 input
| "float32",
"float16",
"int32",
"int8",
"uint8"
| 동일한 랭크 input
| 0에서 5까지 |
MLOpSupportLimits
에는 slice()에
대해 다음 멤버가 있습니다:
slice, 유형은 MLSingleInputSupportLimits-
slice()연산자의 지원 제한입니다.
slice(input, starts, sizes, options)
메서드 단계는 다음과 같습니다:
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input이 false를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
starts의 크기와 sizes의 크기가 둘 다 input의 랭크와 같지 않으면 예외를 발생시킵니다.
TypeError입니다. -
strides를 새 목록으로 둡니다.
-
outputShape을 새 목록으로 둡니다.
-
각각 index에 대해 범위 0부터 inputRank까지에서, 상한은 제외합니다:
-
inputSize를 inputShape[index]로 둡니다.
-
inputSliceSize를 sizes[index]로 둡니다.
-
stride를 strides[index]가 비어 있지 않으면 그 값으로, 그렇지 않으면 1로 둡니다:
-
inputSliceSize가 0이면 예외를 발생시킵니다.
TypeError입니다.0 크기 차원이 허용된다면 이 단계를 수정해야 합니다. [이슈 #391]
-
starts[index] + inputSliceSize가 inputSize보다 크면 예외를 발생시킵니다.
TypeError입니다. -
outputSizeRoundingExcess를 inputSliceSize % stride != 0이면 1로, 그렇지 않으면 0으로 둡니다.
-
outputSize를 floor(inputSliceSize / stride) + outputSizeRoundingExcess로 둡니다:
-
추가합니다 outputSize를 outputShape에.
-
-
outputDesc를 input의 dataType과 outputShape이 주어진 상태에서 MLOperandDescriptor를 생성한 결과로 둡니다.
-
그래프 연결을 구성합니다:
-
output을 outputDesc가 주어진 상태에서 MLOperand를 생성한 결과로 둡니다.
-
operator를 starts, sizes, 그리고 options가 주어진 "slice" 연산의 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
8.9.48. softmax
지정된 축을 따라 N차원 입력 텐서의 softmax 값을 계산합니다.partial interface MLGraphBuilder {MLOperand softmax (MLOperand input , [EnforceRange ]unsigned long axis ,optional MLOperatorOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits softmax ; };
-
input:MLOperand입니다. 입력 N차원 텐서입니다. -
axis:unsigned long스칼라입니다. 축소가 수행될 차원입니다. -
options:MLOperatorOptions입니다. 연산의 선택적 매개변수를 지정합니다.
반환:
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
input
| "float32",
"float16"
| "float32",
"float16"
| 1에서 N까지 | 1에서 5까지 |
| 출력 | 동일한 유형 input
| "float32",
"float16"
| 동일한 랭크 input
| 1에서 5까지 |
MLOpSupportLimits
에는 softmax()에
대해 다음 멤버가 있습니다:
softmax, 유형은 MLSingleInputSupportLimits-
softmax()연산자의 지원 제한입니다.
softmax(input, axis, options)
메서드 단계는 다음과 같습니다:
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input이 false를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
input의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름) 예외를 발생시킵니다.
TypeError입니다. -
그래프 연결을 구성합니다:
-
output을 input이 주어진 상태에서 MLOperand를 복사한 결과로 둡니다.
-
operator를 axis 및 options가 주어진 "softmax" 연산의 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
이 연산의 동작은 다른 연산을 사용하여 일반적으로 에뮬레이션할 수 있으며 다음과 같습니다. 다만 사용자 에이전트에는 일반적으로 더 효율적인 구현이 있습니다. 기반 플랫폼이 연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로 사용할 수 있습니다.
function softmax( builder, input, axis) { // 이 샘플은 결과의 수치적 안정성을 높이기 위해 입력 값 자체의 지수 대신 // 최댓값까지의 거리의 지수를 계산하는 잘 알려진 구현 기법 [1]을 // 사용합니다. // // [1]: https://cs231n.github.io/linear-classify/#softmax const maxX= builder. reduceMax( input, { axes: [ axis], keepDimensions: true }); const expX= builder. exp( builder. sub( input, maxX)); return builder. div( expX, builder. reduceSum( expX, { axes: [ axis], keepDimensions: true })); }
8.9.49. softplus
입력 텐서의 softplus 함수를 계산합니다. 계산은ln(1 + exp(x)) 식을 따릅니다.
partial interface MLGraphBuilder {MLOperand softplus (MLOperand input ,optional MLOperatorOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits softplus ; };
-
input:MLOperand입니다. 입력 텐서입니다. -
options:MLOperatorOptions입니다. 연산의 선택적 매개변수를 지정합니다.
반환:
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
input
| "float32",
"float16"
| "float32",
"float16"
| N | 0에서 5까지 |
| 출력 | 동일한 유형 input
| "float32",
"float16"
| 동일한 랭크 input
| 0에서 5까지 |
MLOpSupportLimits
에는 softplus()에
대해 다음 멤버가 있습니다:
softplus, 유형은 MLSingleInputSupportLimits-
softplus()연산자의 지원 제한입니다.
softplus(input, options)
메서드 단계는 다음과 같습니다:
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input이 false를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
input의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름) 예외를 발생시킵니다.
TypeError입니다. -
그래프 연결을 구성합니다:
-
output을 input이 주어진 상태에서 MLOperand를 복사한 결과로 둡니다.
-
operator를 "softplus" 연산과 options에 대한 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
이 연산의 동작은 다른 연산을 사용하여 일반적으로 에뮬레이션할 수 있으며 다음과 같습니다. 다만 사용자 에이전트에는 일반적으로 더 효율적인 구현이 있습니다. 기반 플랫폼이 연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로 사용할 수 있습니다.
function softplus( builder, input) { return builder. log( builder. add( builder. exp( input), builder. constant( input. dataType, 1 ))); }
8.9.50. softsign
입력 텐서의 softsign 함수를 계산합니다. 계산은x / (1 + |x|) 식을 따릅니다.
partial interface MLGraphBuilder {MLOperand softsign (MLOperand input ,optional MLOperatorOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits softsign ; };
이 연산의 동작은 다른 연산을 사용하여 일반적으로 에뮬레이션할 수 있으며 다음과 같습니다. 다만 사용자 에이전트에는 일반적으로 더 효율적인 구현이 있습니다. 기반 플랫폼이 연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로 사용할 수 있습니다.
function softsign( builder, input) { return builder. div( input, builder. add( builder. constant( input. dataType, 1 ), builder. abs( input))); }
-
input:MLOperand입니다. 입력 텐서입니다. -
options:MLOperatorOptions입니다. 연산의 선택적 매개변수를 지정합니다.
반환:
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
input
| "float32",
"float16"
| "float32",
"float16"
| N | 0에서 5까지 |
| 출력 | 동일한 유형 input
| "float32",
"float16"
| 동일한 랭크 input
| 0에서 5까지 |
MLOpSupportLimits
에는 softsign()에
대해 다음 멤버가 있습니다:
softsign, 유형은 MLSingleInputSupportLimits-
softsign()연산자의 지원 제한입니다.
softsign(input, options)
메서드 단계는 다음과 같습니다:
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input이 false를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
input의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름) 예외를 발생시킵니다.
TypeError입니다. -
그래프 연결을 구성합니다:
-
output을 input이 주어진 상태에서 MLOperand를 복사한 결과로 둡니다.
-
operator를 "softsign" 연산과 options에 대한 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
8.9.51. split
지정된 축을 따라 입력 텐서를 여러 하위 텐서로 분할합니다.dictionary :MLSplitOptions MLOperatorOptions { [EnforceRange ]unsigned long axis = 0; };partial interface MLGraphBuilder {sequence <MLOperand >split (MLOperand input , ([EnforceRange ]unsigned long or sequence <[EnforceRange ]unsigned long >)splits ,optional MLSplitOptions options = {}); };dictionary {MLSplitSupportLimits MLTensorLimits input ;MLTensorLimits outputs ; };partial dictionary MLOpSupportLimits {MLSplitSupportLimits split ; };
-
input:MLOperand입니다. 입력 텐서입니다. -
splits:unsigned long또는 sequence<unsigned long>입니다.unsigned long이면 축을 따라 출력 텐서 수를 지정합니다. 이 수는input의axis방향 차원 크기를 정확히 나누어야 합니다. sequence<unsigned long>이면 각 출력 텐서의axis방향 크기를 지정합니다. 크기의 합은input의axis방향 차원 크기와 같아야 합니다. -
options: 선택적MLSplitOptions입니다. 연산의 선택적 매개변수입니다.
반환: sequence<MLOperand>.
분할된 출력 텐서입니다. splits
가 unsigned long이면
출력의 크기는 splits와
같습니다.
각 출력 텐서의 shape은 input과
같지만,
axis의
차원 크기는
input의
axis
방향 차원 크기를
splits로
나눈 몫과 같습니다.
splits
가 sequence<unsigned long>이면
출력의 크기는 splits의
크기와
같습니다.
i번째 출력 텐서의 shape은 input과
같지만
axis
방향의
차원 크기는 splits[i]입니다.
MLSplitOptions
에는 다음 멤버가 있습니다:
axis, 유형은 unsigned long이며 기본값은0-
분할할 차원입니다. 그 값은 입력 텐서의 랭크가 N일 때 [0, N-1] 범위에 있어야 합니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
input
| 모두 | "float32",
"float16",
"int32"
| 1에서 N까지 | 1에서 5까지 |
| 출력 | 동일한 유형 input
| "float32",
"float16",
"int32"
| 동일한 랭크 input
| 1에서 5까지 |
MLSplitSupportLimits
에는 다음 멤버가 있습니다:
input, 유형은 MLTensorLimits-
MLTensorLimits입력 피연산자에 대한 것입니다. outputs, 유형은 MLTensorLimits-
MLTensorLimits모든 출력 피연산자에 대한 것입니다.
MLOpSupportLimits
에는 split()에
대해 다음 멤버가 있습니다:
split, 유형은 MLSplitSupportLimits-
split()연산자의 지원 제한입니다.
split(input, splits, options)
메서드 단계는 다음과 같습니다:
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input이 false를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
axis를 options.
axis로 둡니다. -
splits가
unsigned long이면: -
splits가 sequence<
unsigned long>이면: -
그래프 연결을 구성합니다:
-
operator를 splits와 options가 주어진 "split" 연산의 연산자로 둡니다.
-
outputs를 새 목록으로 둡니다.
-
각각 index에 대해 범위 0부터 splitCount까지에서, 상한은 제외합니다:
-
operand를 input이 주어진 상태에서 MLOperand를 복사한 결과로 둡니다.
-
splits가
unsigned long이면 newDimension을 operand의 shape[axis] / splits로 둡니다. -
그렇지 않으면 newDimension을 splits[index]로 둡니다.
-
operand의 shape[axis]를 newDimension으로 설정합니다.
-
operand.
[[operator]]를 operator로 설정합니다. -
추가합니다 operand를 outputs에.
-
-
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 outputs로 설정합니다.
-
-
outputs를 반환합니다.
이 연산의 동작은 다른 연산을 사용하여 일반적으로 에뮬레이션할 수 있으며 다음과 같습니다. 다만 사용자 에이전트에는 일반적으로 더 효율적인 구현이 있습니다. 기반 플랫폼이 연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로 사용할 수 있습니다.
function split( builder, input, splits, options) { // 이 샘플은 splits 매개변수가 배열인 경우를 보여줍니다. const outputs= []; const inputShape= input. shape; const inputRank= inputShape. length; let starts= Array( inputRank). fill( 0 ); let sizes= inputShape; let start= 0 ; for ( const sizeof splits) { starts[ options. axis] = start; sizes[ options. axis] = size; outputs. push( builder. slice( input, starts, sizes)); start+= size; } return outputs; }
8.9.52. tanh
입력 텐서의 쌍곡 탄젠트 함수를 계산합니다. 계산은(exp(2 * x) - 1) / (exp(2 * x) + 1) 식을 따릅니다.
partial interface MLGraphBuilder {MLOperand tanh (MLOperand input ,optional MLOperatorOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits tanh ; };
-
input:MLOperand입니다. 입력 텐서입니다. -
options:MLOperatorOptions입니다. 연산의 선택적 매개변수를 지정합니다.
반환:
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
input
| "float32",
"float16"
| "float32",
"float16"
| N | 0에서 5까지 |
| 출력 | 동일한 유형 input
| "float32",
"float16"
| 동일한 랭크 input
| 0에서 5까지 |
MLOpSupportLimits
에는 tanh()에
대해 다음 멤버가 있습니다:
tanh, 유형은 MLSingleInputSupportLimits-
tanh()연산자의 지원 제한입니다.
tanh(input, options) 메서드
단계는 다음과 같습니다:
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input이 false를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
input의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름) 예외를 발생시킵니다.
TypeError입니다. -
그래프 연결을 구성합니다:
-
output을 input이 주어진 상태에서 MLOperand를 복사한 결과로 둡니다.
-
operator를 options가 주어진 "tanh" 연산의 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
이 연산의 동작은 다른 연산을 사용하여 일반적으로 에뮬레이션할 수 있으며 다음과 같습니다. 다만 사용자 에이전트에는 일반적으로 더 효율적인 구현이 있습니다. 기반 플랫폼이 연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로 사용할 수 있습니다.
function tanh( builder, input) { return builder. div( builder. sub( builder. exp( builder. mul( builder. constant( input. dataType, 2 ), input)), builder. constant( input. dataType, 1 )), builder. add( builder. exp( builder. mul( builder. constant( input. dataType, 2 ), input)), builder. constant( input. dataType, 1 ))); }
8.9.53. tile
각 차원을 따라 지정된 횟수만큼 텐서를 반복합니다.partial interface MLGraphBuilder {MLOperand tile (MLOperand input ,sequence <unsigned long >repetitions ,optional MLOperatorOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits tile ; };
-
input:MLOperand입니다. 입력 N차원 텐서입니다. -
repetitions: 각 차원을 몇 번 반복할지 나타내는 차원별 개수입니다. 크기는input의 랭크와 같아야 하며, 같은 크기를 유지해야 하는 축에는 1을 사용합니다. -
options: 선택적MLOperatorOptions입니다. 연산의 선택적 매개변수입니다.
반환: MLOperand입니다.
반복된 N차원 텐서입니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
input
| 모두 | "float32",
"float16",
"int32"
| N | 0에서 5까지 |
| 출력 | 동일한 유형 input
| "float32",
"float16",
"int32"
| 동일한 랭크 input
| 0에서 5까지 |
MLOpSupportLimits
에는 tile()에
대해 다음 멤버가 있습니다:
tile, 유형은 MLSingleInputSupportLimits-
tile()연산자의 지원 제한입니다.
tile(input, repetitions, options)
메서드 단계는 다음과 같습니다:
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input이 false를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
repetitions의 크기가 input의 랭크와 같지 않으면 예외를 발생시킵니다.
TypeError입니다. -
repetitions의 값에 0이 포함되어 있으면 예외를 발생시킵니다.
TypeError입니다.0 크기 차원이 허용된다면 이 단계를 수정해야 합니다. [이슈 #391]
-
outputShape을 input의 shape의 복사본으로 둡니다.
-
각각 index에 대해 범위 0부터 outputShape의 크기까지에서, 상한은 제외합니다:
-
outputShape[index]를 outputShape[index] * repetitions[index]로 설정합니다.
-
-
outputDescriptor를 input의 dataType과 outputShape이 주어진 상태에서 MLOperandDescriptor를 생성한 결과로 둡니다.
-
그래프 연결을 구성합니다:
-
output을 outputDescriptor가 주어진 상태에서 MLOperand를 생성한 결과로 둡니다.
-
operator를 options가 주어진 "tile" 연산의 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
8.9.54. transpose
permutation에
따라 입력 텐서의 차원을 순열합니다.
dictionary :MLTransposeOptions MLOperatorOptions {sequence <[EnforceRange ]unsigned long >permutation ; };partial interface MLGraphBuilder {MLOperand transpose (MLOperand input ,optional MLTransposeOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits transpose ; };
MLTransposeOptions
에는 다음 멤버가 있습니다:
permutation, 유형은sequence<[EnforceRange] unsigned long>-
출력 shape을 순열하는 데 사용하는 값입니다. 기본값은 [N-1, ..., 0]이며, 여기서 N은 입력 텐서의 랭크입니다. 예를 들어 3차원 텐서의 경우 [2,1,0]입니다. 이러한 기본값으로 인해 출력은 입력의 전치된 텐서가 됩니다. 지정하는 경우 값의 개수는 입력 텐서의 랭크와 같아야 하며, 값은 중복 없이 0에서 N-1까지의 범위에 있어야 합니다.
-
input:MLOperand입니다. 입력 N차원 텐서입니다. -
options: 선택적MLTransposeOptions입니다. 연산의 선택적 매개변수입니다.
반환: MLOperand입니다.
순열되거나 전치된 N차원 텐서입니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
input
| 모두 | "float32",
"float16",
"int32"
| N | 0에서 5까지 |
| 출력 | 동일한 유형 input
| "float32",
"float16",
"int32"
| 동일한 랭크 input
| 0에서 5까지 |
MLOpSupportLimits
에는 transpose()에
대해 다음 멤버가 있습니다:
transpose, 유형은 MLSingleInputSupportLimits-
transpose()연산자의 지원 제한입니다.
transpose(input, options)
메서드 단계는 다음과 같습니다:
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input이 false를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
options.
permutation이 존재하지 않으면 options.permutation을 input의 shape에 대한 모든 인덱스의 역순 시퀀스로 둡니다. -
그렇지 않고 options.
permutation이 존재하면: -
그래프 연결을 구성합니다:
-
output을 input이 주어진 상태에서 MLOperand를 복사한 결과로 둡니다.
-
operator를 options가 주어진 "transpose" 연산의 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
8.9.55. triangular
2차원 텐서(행렬)가 주어지면 입력 텐서의 위쪽 또는 아래쪽 삼각 부분을 포함하는 2차원 텐서를 반환합니다. 입력 텐서가 2차원보다 크면 행렬 배치로 처리하며 결과는 동일한 shape을 가집니다.dictionary :MLTriangularOptions MLOperatorOptions {boolean upper =true ; [EnforceRange ]long diagonal = 0; };partial interface MLGraphBuilder {MLOperand triangular (MLOperand input ,optional MLTriangularOptions options = {}); };partial dictionary MLOpSupportLimits {MLSingleInputSupportLimits triangular ; };
MLTriangularOptions
에는 다음 멤버가 있습니다:
upper, 유형은 boolean이며 기본값은true-
입력 행렬의 위쪽 또는 아래쪽 부분 중 어느 쪽을 출력에 유지할지 나타냅니다. true이면 위쪽 부분을 유지합니다.
diagonal, 유형은 long이며 기본값은0-
입력 행렬의 주대각선 위나 아래에서 몇 개의 대각선을 유지하거나 제외할지 지정합니다. 값이 0이면 주대각선 이외의 대각선에는 영향을 주지 않습니다.
-
input:MLOperand입니다. 최소 2차원인 입력 텐서입니다. -
options: 선택적MLTriangularOptions입니다. 연산의 선택적 매개변수입니다.
반환: MLOperand입니다.
삼각 행렬 또는 입력과 동일한 shape을 가진 행렬 배치를 나타내는
출력 텐서입니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
input
| 모두 | "float32",
"float16"
| 2에서 N까지 | 2에서 5까지 |
| 출력 | 동일한 유형 input
| "float32",
"float16"
| 동일한 랭크 input
| 2에서 5까지 |
MLOpSupportLimits
에는 triangular()에
대해 다음 멤버가 있습니다:
triangular, 유형은 MLSingleInputSupportLimits-
triangular()연산자의 지원 제한입니다.
triangular(input, options)
메서드 단계는 다음과 같습니다:
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 input이 false를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
input의 랭크가 해당 허용되는 랭크 중 하나가 아니면(이 표에 따름) 예외를 발생시킵니다.
TypeError입니다. -
그래프 연결을 구성합니다:
-
output을 input이 주어진 상태에서 MLOperand를 복사한 결과로 둡니다.
-
operator를 options가 주어진 "triangular" 연산의 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 input으로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
서로 다른 diagonal 설정에서 triangular가 동작하는 방식의 예입니다.
// 입력: // [[7, 1, 2], // [9, 4, 8], // [2, 6, 3]] const input= builder. constant( { dataType: 'float32' , shape: [ 3 , 3 ]}, new Float32Array([ 7 , 1 , 2 , 9 , 4 , 8 , 2 , 6 , 3 ])); // 상삼각 행렬: // [[7, 1, 2], // [0, 4, 8], // [0, 0, 3]] const upper= builder. triangular( input); // 추가 대각선 한 세트를 제외한 상삼각 행렬: // [[0, 1, 2], // [0, 0, 8], // [0, 0, 0]] const upperPositive= builder. triangular( input, { diagonal: 1 }); // 추가 대각선 한 세트를 유지한 상삼각 행렬: // [[7, 1, 2], // [9, 4, 8], // [0, 6, 3]] const upperNegative= builder. triangular( input, { diagonal: - 1 }); // 하삼각 행렬: // [[7, 0, 0], // [9, 4, 0], // [2, 6, 3]] const lower= builder. triangular( input, { upper: false }); // 추가 대각선 한 세트를 유지한 하삼각 행렬: // [[7, 1, 0], // [9, 4, 8], // [2, 6, 3]] const lowerPositive= builder. triangular( input, { upper: false , diagonal: 1 }); // 추가 대각선 한 세트를 제외한 하삼각 행렬: // [[0, 0, 0], // [9, 0, 0], // [2, 6, 0]] const lowerNegative= builder. triangular( input, { upper: false , diagonal: - 1 }) // 배치가 두 개인 하삼각 행렬: // [[[7, 0, 0], // [9, 4, 0], // [2, 6, 3]], // [[1, 0, 0], // [4, 5, 0], // [7, 8, 9]]] const lowerWithBatches= builder. triangular( input, { upper: false });
8.9.56. where
trueValue
또는 falseValue
텐서에서 대응하는 condition
텐서의 값에 따라 값을 선택합니다. 0이 아니면 true이고 0이면 false입니다. condition
텐서는 대개 요소별 논리 연산 중 하나의 출력입니다.
연산은 브로드캐스트되며 [numpy-broadcasting-rule]을 따릅니다. 입력 텐서는 양방향 브로드캐스트 가능해야 합니다. 출력 텐서의 랭크는 입력 텐서의 최대 랭크입니다. 출력 텐서의 각 차원에 대해 그 크기는 입력 텐서에서 해당 차원을 따른 최대 크기입니다.
partial interface MLGraphBuilder {MLOperand where (MLOperand condition ,MLOperand trueValue ,MLOperand falseValue ,optional MLOperatorOptions options = {}); };dictionary {MLWhereSupportLimits MLTensorLimits condition ;MLTensorLimits trueValue ;MLTensorLimits falseValue ;MLTensorLimits output ; };partial dictionary MLOpSupportLimits {MLWhereSupportLimits where ; };
-
condition:MLOperand입니다. 조건 텐서입니다. -
trueValue:MLOperand입니다. 대응하는 요소의 조건이 true로 설정된 경우 값을 선택하는 텐서입니다. -
falseValue:MLOperand입니다. 대응하는 요소의 조건이 false로 설정된 경우 값을 선택하는 텐서입니다. -
options:MLOperatorOptions입니다. 연산의 선택적 매개변수를 지정합니다.
반환: MLOperand입니다.
trueValue
또는 falseValue
텐서에서 요소별로 선택한 값을 포함하는 출력 텐서입니다.
| 피연산자 | 허용되는 데이터 유형 | 필수 데이터 유형 | 허용되는 랭크 | 필수 랭크 |
|---|---|---|---|---|
condition
| "uint8"
| "uint8"
| N | 0에서 5까지 |
trueValue
| 모두 | "float32",
"float16",
"int32"
| N | 0에서 5까지 |
falseValue
| 동일한 유형 trueValue
| "float32",
"float16",
"int32"
| N | 0에서 5까지 |
| 출력 | 동일한 유형 trueValue
| "float32",
"float16",
"int32"
| N | 0에서 5까지 |
MLWhereSupportLimits
에는 다음 멤버가 있습니다:
condition, 유형은 MLTensorLimits-
MLTensorLimitscondition 피연산자에 대한 것입니다. trueValue, 유형은 MLTensorLimits-
MLTensorLimitstrueValue 피연산자에 대한 것입니다. falseValue, 유형은 MLTensorLimits-
MLTensorLimitsfalseValue 피연산자에 대한 것입니다. output, 유형은 MLTensorLimits-
MLTensorLimits출력 피연산자에 대한 것입니다.
MLOpSupportLimits
에는 where()에
대해 다음 멤버가 있습니다:
where, 유형은 MLWhereSupportLimits-
where()연산자의 지원 제한입니다.
where(condition, trueValue, falseValue, options)
메서드 단계는 다음과 같습니다:
-
this가 빌드할 수 없는 상태이면 예외를 발생시킵니다. "
InvalidStateError"DOMException입니다. -
피연산자를 검증할 때 this와 condition, trueValue 및 falseValue 중 하나가 false를 반환하면 예외를 발생시킵니다.
TypeError입니다. -
condition, trueValue 또는 falseValue 중 하나의 dataType이 해당 허용되는 데이터 유형 중 하나가 아니면(이 표에 따름) 예외를 발생시킵니다.
TypeError입니다. -
outputShape을 trueValue의 shape과 falseValue의 shape을 양방향 브로드캐스트한 결과로 둡니다.
-
outputShape을 condition의 shape과 outputShape을 양방향 브로드캐스트한 결과로 설정합니다.
-
descriptor를 trueValue의 dataType과 outputShape이 주어진 상태에서 MLOperandDescriptor를 생성한 결과로 둡니다.
-
그래프 연결을 구성합니다:
-
output을 MLOperand를 생성한 결과로 두며 this와 descriptor가 주어집니다.
-
operator를 condition, trueValue, falseValue, 그리고 options가 주어진 "where" 연산의 연산자로 둡니다.
-
output.
[[operator]]를 operator로 설정합니다. -
operator의 입력을 condition, trueValue 및 falseValue로 설정합니다.
-
operator의 출력을 output으로 설정합니다.
-
-
output을 반환합니다.
이 연산의 동작은 다른 연산을 사용하여 일반적으로 에뮬레이션할 수 있으며 다음과 같습니다. 다만 사용자 에이전트에는 일반적으로 더 효율적인 구현이 있습니다. 기반 플랫폼이 연산을 직접 지원하지 않는 경우 이 분해를 구현을 안내하는 템플릿으로 사용할 수 있습니다.
function where( builder, condition, trueValue, falseValue) { const c= builder. clamp( condition, { 'minValue' : 0 , 'maxValue' : 1 }); builder. add( builder. mul( trueValue, builder. cast( c, trueValue. dataType)), builder. mul( falseValue, builder. cast( builder. logicalNot( c), falseValue. dataType))); }
9. 알고리즘
9.1. 브로드캐스팅
브로드캐스팅은 그래프 구성과 계산 중에 WebNN이 shape이 서로 다른 텐서를 어떻게 처리하는지 설명합니다. 이는 [NumPy]의 영향을 크게 받으며 [numpy-broadcasting-rule]을 따릅니다. 대략적으로 말하면 더 작은 텐서에 대한 연산을 더 큰 텐서의 shape 전체에 "브로드캐스트"하여 같은 데이터를 복사하지 않고 반복 적용할 수 있게 합니다.
가장 간단한 예는 add()
또는 mul()과
같은 요소별
이항 연산을 통해 스칼라 상수를 N차원 텐서에 적용하는 것입니다.
스칼라 상수의 여러 복사본을 포함하는 일치하는 N차원 텐서를 할당하고 채울 필요 없이
이러한 요소별 연산은 스칼라 상수를 직접 사용하고
스칼라 값을 N차원 텐서 전체에 브로드캐스트할 수 있습니다. 다음 사항을 고려하면 같은
논리가 다른 차원의 텐서에도 적용됩니다.
입력 텐서의 shape은 호환되어야 합니다. 첫 번째 텐서를
크기가 1인 축을 따라 반복하거나 새 차원에 걸쳐 반복하여, 마지막(가장 오른쪽) 차원부터 시작해
"늘릴" 수 있다면 한 텐서는 다른 텐서에 단방향
브로드캐스트 가능합니다.
예를 들어 [4] 텐서는 5번 반복하여 [5, 4] 텐서로 브로드캐스트할 수 있습니다.
[1] 텐서는 마지막 차원에서 4번, 그 앞 차원에서 5번 반복하여 [5,4] 텐서로 브로드캐스트할 수 있습니다.
단방향 브로드캐스팅은 대상 텐서 shape이 명시적으로 주어지는 expand()
같은 연산에 중요합니다.
두 텐서가 마지막 차원부터 시작하여 서로의 여러 차원 전체에 걸쳐 상호 "늘어날"(반복될) 수 있다면 양방향 브로드캐스트 가능합니다. 예를 들어 [5,1] 텐서는 첫 번째 텐서를 마지막 차원에서 6번, 두 번째 텐서를 앞 차원에서 5번 반복하여 [1,6] 텐서와 양방향 브로드캐스트할 수 있습니다. 연산 결과는 [5,6] 텐서가 됩니다. 양방향 브로드캐스팅은 요소별 연산에 편리합니다.
모든 차원을 정수 배수로 업샘플링하여 대상 텐서의 shape에 맞출 수 있다면 텐서는 블록 단위 브로드캐스트 가능합니다. 예를 들어 [4,5] 텐서는 정확한 배수이므로 (16 % 4 = 0, 10 % 5 = 0) 첫 번째 차원에서 각 요소를 4번, 마지막 차원에서 각 요소를 2번 반복하여 [16,10] 텐서로 블록 단위 브로드캐스트할 수 있습니다(예: 마지막 차원의 값 [1,2,3,4,5]는 [1,1,2,2,3,3,4,4,5,5]로 반복됩니다). 그러나 [4,5] 텐서는 두 차원 모두 나머지가 0이 아니므로 [9,3] 텐서와 호환되지 않습니다(9 % 4 = 1, 3 % 5 = 3). 블록 단위 브로드캐스팅은 메모리를 절약하기 위해 더 큰 블록에서 공통 값을 공유하는 데 유용합니다. 두 텐서는 동일한 랭크를 가져야 하며 출력 shape은 더 작은 텐서가 업샘플링되는 대상 텐서의 shape입니다.
일부 연산은 특수한 의미의 브로드캐스팅을 허용합니다. 예를 들어 matmul()
은 입력 텐서의 마지막 두 차원을 행렬의 행과 열로 처리하며 첫 번째 행렬의
열 수는 두 번째 행렬의 행 수와 같아야 합니다. 행렬
곱셈은 추가 차원 전체에 양방향 브로드캐스트되며 입력 텐서를
곱할 행렬의 스택으로 처리합니다.
shapeFrom 및 shapeTo의 shape을 단방향 브로드캐스트하려면 다음 단계를 수행합니다. shapeFrom과 shapeTo는 텐서 차원을 나타내는 양의 정수 목록이며, 이 단계는 양의 정수의 새 목록 또는 실패를 반환합니다.
-
sizeFrom을 shapeFrom의 크기로 둡니다.
-
sizeTo를 shapeTo의 크기로 둡니다.
-
sizeFrom > sizeTo이면 실패를 반환합니다.
-
paddedShapeFrom을 shapeFrom의 복제본으로 둡니다.
-
paddedShapeFrom의 크기가 sizeTo보다 작은 동안 paddedShapeFrom 앞에 1을 추가합니다.
-
outputShape을 새 목록으로 둡니다.
-
각각 index에 대해 범위 0부터 sizeTo까지에서, 상한은 제외합니다:
-
dimFrom을 paddedShapeFrom[index]로 둡니다.
-
dimTo를 shapeTo[index]로 둡니다.
-
dimTo가 dimFrom과 같지 않고 dimFrom도 1과 같지 않으면 실패를 반환합니다.
-
추가합니다 dimTo를 outputShape에.
-
-
outputShape을 반환합니다.
shapeFrom은 shapeFrom과 shapeTo를 단방향 브로드캐스트한 결과가 실패가 아니라면 shapeTo로 단방향 브로드캐스트 가능합니다.
shapeA와 shapeB의 shape을 양방향 브로드캐스트하려면 다음 단계를 수행합니다. shapeA와 shapeB는 텐서 차원을 나타내는 양의 정수 목록이며, 이 단계는 양의 정수의 새 목록 또는 실패를 반환합니다.
-
sizeA를 shapeA의 크기로 둡니다.
-
sizeB를 shapeB의 크기로 둡니다.
-
outputSize를 sizeA와 sizeB 중 최댓값으로 둡니다.
-
paddedA를 shapeA의 복제본으로 둡니다.
-
paddedB를 shapeB의 복제본으로 둡니다.
-
outputShape을 새 목록으로 둡니다.
-
각각 index에 대해 범위 0부터 outputSize까지에서, 상한은 제외합니다:
-
dimA를 paddedA[index]로 둡니다.
-
dimB를 paddedB[index]로 둡니다.
-
dimA가 dimB와 같지 않고 dimA가 1과 같지 않으며 dimB도 1과 같지 않으면 실패를 반환합니다.
-
추가합니다 dimA와 dimB 중 최댓값을 outputShape에.
-
-
outputShape을 반환합니다.
shapeA는 shapeA와 shapeB를 양방향 브로드캐스트한 결과가 실패가 아니라면 shapeB로 양방향 브로드캐스트 가능합니다.
shapeFrom과 shapeTo의 shape을 블록 단위로 브로드캐스트하려면 다음 단계를 수행합니다. shapeFrom과 shapeTo는 텐서 차원을 나타내는 양의 정수 목록이며, 이 단계는 true 또는 false를 반환합니다.
shapeFrom은 shapeFrom과 shapeTo를 블록 단위로 브로드캐스트한 결과가 true이면 shapeTo로 블록 단위 브로드캐스트 가능합니다.
9.2. 캐스팅
MLNumber
또는 double로
전달된 매개변수를 입력 또는 출력 MLOperand의
MLOperandDataType에
맞게 변환해야 하는 알고리즘에서는
명시적 숫자 캐스팅을 사용합니다.
숫자 x를 주어진 MLOperandDataType
dataType으로 캐스트하려면
다음 단계를 수행합니다. 이 단계는 숫자를 반환합니다.
-
dataType에 따라 분기합니다:
"float32"-
ConvertToFloat(x, 32)를 반환합니다.
"float16"-
ConvertToFloat(x, 16)를 반환합니다.
"int64"-
ConvertToInt(x, 64, "signed")를 반환합니다.
"uint64"-
ConvertToInt(x, 64, "unsigned")를 반환합니다.
"int32"-
ConvertToInt(x, 32, "signed")를 반환합니다.
"uint32"-
ConvertToInt(x, 32, "signed")를 반환합니다.
"int8"-
ConvertToInt(x, 8, "signed")를 반환합니다.
"uint8"-
ConvertToInt(x, 8, "unsigned")를 반환합니다.
참고: 캐스트의 입력은 Infinity, -Infinity 및 NaN 특수 값을 포함하는 범위와 정밀도에 제한이 없는 추상 숫자입니다. 출력도 추상 숫자이지만 지정된 유형으로 정확히 표현할 수 있습니다.
-
x가 NaN이면 NaN을 반환합니다.
-
bitLength에 따라 분기합니다:
- 32
-
-
upperBound를 2128로 둡니다.
-
lowerBound를 -2128로 둡니다.
-
S를 -0을 제외한 [IEEE-754-2019] binary32 부동 소수점 값의 집합으로 두되, 특수 값 upperBound 및 lowerBound를 추가합니다.
-
- 16
-
-
upperBound를 216으로 둡니다.
-
lowerBound를 -216으로 둡니다.
-
S를 -0을 제외한 [IEEE-754-2019] binary16 부동 소수점 값의 집합으로 두되, 특수 값 upperBound 및 lowerBound를 추가합니다.
-
-
y를 S에서 x와 가장 가까운 숫자로 두며, 두 개의 동일하게 가까운 값이 있으면 유효숫자가 짝수인 숫자를 선택합니다. 이 목적에서는 두 특수 값 lowerBound 및 upperBound의 유효숫자를 짝수로 간주합니다.
-
y가 upperBound이면 +Infinity를 반환합니다.
-
y가 lowerBound이면 -Infinity를 반환합니다.
-
y가 +0이고 x가 음수이면 -0을 반환합니다.
-
y를 반환합니다.
참고: 이는 [WEBIDL]의 정의를 기반으로 하지만 16비트 부동 소수점 값도 다루도록 확장되었습니다.
-
signedness가 "unsigned"이면:
-
lowerBound를 0으로 둡니다.
-
upperBound를 2bitLength - 1로 둡니다.
-
-
그렇지 않으면:
-
lowerBound를 -(2bitLength - 1)로 둡니다.
-
upperBound를 2bitLength - 1 - 1로 둡니다.
-
-
x가 -0이면 x를 +0으로 설정합니다.
-
x가 NaN이면 +0을 반환합니다.
-
x를 min(max(x, lowerBound), upperBound)로 설정합니다.
-
x를 가장 가까운 정수로 반올림하되 두 정수의 정확히 중간이면 짝수 정수를 선택하고 -0 대신 +0을 선택합니다.
-
x를 반환합니다.
참고: 이는 [WEBIDL]의 정의를 기반으로 하며 다음과 같은 차이가 있습니다. 64비트 정수를 특별히 처리하지 않고, 입력 x는 추상 숫자이며, clamping은 항상 수행됩니다.
9.3. 기타
[INFRA]에 정의가 제공되면 이를 제거하십시오. [whatwg/infra 이슈 #664]
10. 예제
constant1 ---+
+--- Add ---> intermediateOutput1 ---+
input1 ---+ |
+--- Mul---> output
constant2 ---+ |
+--- Add ---> intermediateOutput2 ---+
input2 ---+
다음 코드는 그래프를 구현합니다:
// 4차원 텐서를 사용합니다. const TENSOR_SHAPE= [ 1 , 2 , 2 , 2 ]; const TENSOR_SIZE= 8 ; const context= await navigator. ml. createContext(); const builder= new MLGraphBuilder( context); // MLOperandDescriptor 객체를 생성합니다. const desc= { dataType: 'float32' , shape: TENSOR_SHAPE}; // constant1은 값이 0.5인 상수 MLOperand입니다. const constantBuffer1= new Float32Array( TENSOR_SIZE). fill( 0.5 ); const constant1= builder. constant( desc, constantBuffer1); // input1은 입력 MLOperand 중 하나입니다. 그 값은 // 실행 전에 설정됩니다. const input1= builder. input( 'input1' , desc); // constant2는 값이 0.5인 또 다른 상수 MLOperand입니다. const constantBuffer2= new Float32Array( TENSOR_SIZE). fill( 0.5 ); const constant2= builder. constant( desc, constantBuffer2); // input2는 또 다른 입력 MLOperand입니다. 그 값은 실행 전에 설정됩니다. const input2= builder. input( 'input2' , desc); // intermediateOutput1은 첫 번째 Add 연산의 출력입니다. const intermediateOutput1= builder. add( constant1, input1); // intermediateOutput2는 두 번째 Add 연산의 출력입니다. const intermediateOutput2= builder. add( constant2, input2); // output은 Mul 연산의 출력 MLOperand입니다. const output= builder. mul( intermediateOutput1, intermediateOutput2);
11. 연산자 에뮬레이션
이 절은 비규범적입니다.
다른 신경망 추론 API에 있는 연산은 WebNN에 있는 연산을 사용하여 에뮬레이션할 수 있는 경우가 많습니다.
11.1. squeeze
squeeze 연산은
입력에서 크기가 1인 지정된 모든 차원을 제거한 텐서를 반환합니다. 다음과 같이 reshape()
연산을 사용하여 일반적으로 구현할 수 있습니다:
function squeeze( builder, input, axes) { if ( ! axes) axes= []; if ( ! axes. length) input. shape. forEach(( item, i) => { axes. push( i); }); const shape= Array. from ( input. shape); for ( let axisof axes. sort(). reverse()) if ( axis< shape. length&& shape[ axis] == 1 ) shape. splice( axis, 1 ); return builder. reshape( input, shape); }
11.2. unsqueeze
11.3. flatten
flatten 연산은
입력을 1차원 텐서로 reshape합니다. 다음과 같이 reshape()
연산을 사용하여 일반적으로 구현할 수 있습니다:
function flatten( builder, input, axis) { if ( axis> input. shape. length) return input; const before= axis. slice( 0 , axis). reduce(( a, b) => a* b, 1 ); const after= axis. slice( axis, input. shape. length). reduce(( a, b) => a* b, 1 ); return builder. reshape( input, [ before, after]); }
12. 부록
12.1. MLOperandDataType
및 ArrayBufferView
호환성
MLOperandDataType
| ArrayBufferView
|
|---|---|
float32
| Float32Array
|
float16
| Float16Array
|
int64
| BigInt64Array
|
uint64
| BigUint64Array
|
int32
| Int32Array
|
uint32
| Uint32Array
|
int8
| Int8Array
|
uint8
| Uint8Array
|
Float16Array
는 설계가 완료되었음을 나타내는 ECMA Stage 3에 있습니다.
네이티브 구현보다 먼저 이 유형을 활성화하려는 구현자는 Uint16Array를
통해 원시
비트를 전달하여 유형을 에뮬레이션할 수 있습니다.
[이슈 webnn#373]
13. 감사의 글
이 명세는 Android Neural Networks API C API의 개념을 따릅니다.
사용 사례를 제공해 주신 Tomoyuki Shimizu, Ningxin Hu, Zhiqiang Yu 및 Belem Zhang께 감사드립니다.
API 명세에 기여해 주신 Nikhil Thorat, Daniel Smilkov, Ganesan Ramalingam, Rafael Cintron 및 Benjamin Poulain께 감사드립니다.
웹 아키텍처 적합성, 설계 일관성 및 개발자 사용성을 위해 이 명세를 검토해 주신 Sangwhan Moon과 W3C Technical Architecture Group에 감사드립니다.
알고리즘을 추가하고 이 명세를 탐색하는 경험을 즐겁게 만들어 주신 Zoltan Kis께 감사드립니다. 명세를 현대적인 편집 관례에 맞춰 주신 Joshua Bell께 감사드립니다. 세심한 검토와 의견을 제공해 주신 Ningxin Hu, Lisha Guo, Shiyi Zou, Mingming Xu, Junwei Fu, Bruce Dai 및 Bin Miao께 감사드립니다.
개인정보 보호 및 보안 검토와 피드백을 제공해 주신 W3C Privacy Interest Group에 감사드립니다.
보안 검토와 질문을 제공해 주신 Alex Gough와 Chrome Security 팀에 감사드립니다.
ONNX의 실용적인 지침과 학습 내용을 공유해 주신 Michal Karzynski께 감사드립니다.
피드백과 개인정보 보호 고려 사항을 제공해 주신 Kaustubha Govind와 Chrome 개인정보 보호 검토자들께 감사드립니다.
Chromium 구현 검토와 피드백을 제공해 주신 Jiewei Qian께 감사드립니다.
transformer 지원을 조사하고 권고안을 제공한 Dwayne Robinson, Joshua Lochner 및 Wanming Lin께 감사드립니다. 연산자 적합성과 web-platform-tests 구현을 검토해 주신 Dwayne과 Wanming께도 추가로 감사드립니다.
web-platform-tests가 명세와 함께 계속 발전하도록 지속적으로 기여해 주신 Feng Dai께 감사드립니다.
검토와 제안을 제공해 주신 Fuqiao Xue와 W3C Internationalization Activity에 감사드립니다.
14. 변경 사항
이 절은 비규범적입니다.
이 절은 이전 주요 발행 이후 이 명세에 적용된 변경 사항을 변경 클래스에 따라 문서화합니다.
Candidate Recommendation Snapshot 2024년 4월 11일과 2026년 1월 22일 사이의 상세 변경 사항
새 기능(클래스 4)
- dequantizeLinear, quantizeLinear 및 attention 연산을 포함하는 새 연산자로 연산자 집합 "wave 3" 확장(#805)
- WebNN과 WebGPU 간 버퍼 공유 및 여러 MLGraph에서 재사용하기 위한 인터페이스인 MLTensor API 추가(#787)
- NaN 및 무한대 값을 확인하는 새로운 요소별 연산자인 isNaN 및 isInfinite 연산자 추가 (#858)
- banker’s rounding을 사용하는 새로운 반올림 연산자인 roundEven 연산자 추가(#859)
- ML 가속기를 선택하기 위한 간단한 메커니즘인 가속기 선택 메커니즘 추가(#895)
- WebNN 가용성을 window 및 dedicated worker 이상으로 확장하기 위해 공유 worker와 service worker에 WebNN API 노출 (#823)
- 더 진단하기 쉬운 오류 메시지를 위한 선택적 연산자 레이블 추가(#742)
- 모든 유형의 숫자 입력을 지정하기 위한 통합 유형인 MLNumber 도입(#647)
- 지원 제한에서 랭크 범위를 지정할 수 있도록 opSupportLimits()에 rankRange 추가(#828)
- rankRange 지원을 출력 텐서로 확장하기 위해 연산 출력 텐서에 rankRange 지원(#857)
Neural Processing Unit(NPU) 장치 유형인 MLDeviceType npu 추가(#696)- 이 기능은 장치 선택을 단순화하기 위해 이전 발행 이후 추가되었다가 제거되었습니다. #809를 참조하십시오.- MLContext 및 MLGraph에 destroy() 메서드 추가, 컨텍스트 손실 동작 및 오류 보고 지정 (#744)
- softmax 연산에 선택적 axis 매개변수 추가(#649)
- 출력 데이터 유형 지정을 지원하기 위해 argmin/argmax에 outputDataType 추가(#730)
- resample2d가 모든 축에서 작동하도록 일반화하기 위해 임의의 축 허용(#752)
- resample이 8비트 정수 유형을 지원하도록 Resample 데이터 유형 uint8/int8 추가(#891)
- conv2d 및 pool2d 연산의 피연산자 레이아웃 지원 단순화, pool2d에서 MLRoundingType 제거, 레이아웃 지원 단순화(#770)
- 백엔드 제한과 더 잘 일치하도록 패딩 옵션 제한(#843)
새 기능을 추가하지 않는 기타 변경 사항(클래스 3)
- MLTensor API를 위해 MLContext.compute() 메서드 제거(#795)
- 장치 유형 열거를 제거하여 장치 선택을 단순화하기 위해 MLDeviceType 제거(#809)
- MLOperand 메서드를 readonly 속성으로 변환하고 dataType() 및 shape()을 메서드에서 속성으로 변경(#774)
- MLOperandDescriptor.shape을 필수 속성으로 변경(#764)
- 빌드 메서드를 한 번만 호출하도록 제한하기 위해 MLGraphBuilder.build()를 한 번만 호출할 수 있도록 변경 (#717)
- 시퀀스 기반 상수 생성을 제거하기 위해 constant()의 fillSequence 오버로드 제거(#656)
- 일관성을 위해 매개변수 순서를 바꾸도록 스칼라 constant() 피연산자 메서드의 매개변수 교환(#650)
- argmin/argmax API를 단순화하기 위해 selectLastIndex 매개변수 제거(#722)
- API 전반의 일관성을 위해 cast/constant 매개변수 유형 이름을 dataType으로 변경(#888)
- 순환 네트워크 활성화에 더 구체적인 유형을 사용하기 위해 MLActivation을 MLRecurrentNetworkActivation으로 교체 (#718)
- 더 나은 Unicode 지원을 위해 DOMString을 USVString으로 변경(#715)
- 명확성을 높이기 위해 where의 매개변수 이름 변경(#719)
- 일관성을 위해 MLLstmCellSupportLimits의 멤버 output을 outputs로 변경(#757)
- 적절한 Promise 거부를 위해 파괴된 MLTensor에서 진행 중인 연산의 Promise 거부(#799)
- 데이터 유형 검증 규칙을 적용할 수 있도록 연산의 피연산자 데이터 유형 제약 조건 지정(#646)
- 검증 개선을 위해 여러 연산에 누락된 검증 단계 추가(#820)
- 배열 연산의 검증을 강화하기 위해 pad(), slice(), split()에 누락된 검증 추가 (#690)
- 개선된 순환 네트워크 검증을 위해 GRU/LSTM 검증 단순화, 수정 및 추가(#659)
- GRU 및 LSTM 연산자의 hidden size 검증(#644)
- 전치 컨볼루션에 대한 더 엄격한 검증을 위해 convTranspose2d의 output padding 제한 검증(#631)
- gather 연산 검증 강화(#642)
- 일반적인 검증 개선(#643)
- 리소스 검증 개선(#622)
- 버퍼 전송 오류를 적절히 처리하기 위해 MLNamedArrayBufferViews 전송 알고리즘의 오류 처리 정의(#723)
- 차원 유효 범위를 부호 있는 정수로 업데이트(#738)
- 차원 유효성을 공식화하기 위해 "valid dimension" 개념 도입(#641)
- 객체 생성 시 적절한 Realm 처리를 위해 Realm 지정 보장(#810)
- 나눗셈 연산자의 반올림 명확화(#909)
- pad 스칼라 불일치 수정(#894)
- split 연산의 opSupportLimits 오류 수정(#776)
- softmax() axis 인수에서 적절한 범위 강제를 위해 EnforceRange 사용(#746)
- conv2d 알고리즘에 누락된 inputShape 정의 추가(#680)
- 단방향 브로드캐스트 shape 단계 수정(#663)
- 버퍼 전송 실패 시 compute() Promise 거부 동작 수정(#639)
- 64비트 정수 유형으로 ArrayBufferView 호환성 표 업데이트(#698)
문서 해석에 기능적으로 영향을 주지 않는 변경 사항(클래스 2)
- 체계적인 검증 접근 방식을 위해 피연산자 데이터 유형 및 랭크 검증을 표 기반으로 변경(#657)
- 카테고리별 연산자의 비규범적 표 추가(#868)
- 서로 다른 데이터 유형 간 cast() 연산 동작 명확화(#726)
- resample2d의 보간 알고리즘 명확화(#816)
- 경계 사례를 명확히 하기 위해 빈 axes 및 스칼라 입력에서의 축소 명확화(#741)
- no-op 그래프에 대한 참고 추가(#665)
- 축소 연산 동작을 명확히 하기 위해 축소 연산의 keepDimensions에 대한 참고 추가(#648)
- 에뮬레이션 문서 재구성(#598)
- reduceLogSum, reduceLogSumExp 및 reduceSumSquare 분해 추가(#637)
- clamp() minValue == maxValue 상호운용성 문제에 대한 오래된 참고 제거(#684)
- 명세 상용구 메타데이터 정보 업데이트(#769)
- 아키텍처 리소스 경합 고려 사항 추가(#765)
- Unicode에 대한 보안 고려 사항 추가(#851)
- 계산 제어 흐름 공격에 대한 보안 고려 사항 추가(#725)
- 개인정보 보호 고려 사항 개정(#890)
- opSupportLimits() fingerprinting에 대한 개인정보 보호 고려 사항 추가(#881)
- 접근성 고려 사항 추가(#869)
- label 사용에 관한 국제화 참고 추가(#841)
편집상 변경(클래스 2)
- 다양한 편집 개선(#834)
- 다양한 스타일 및 표현 조정(#797)
- 문법 및 철자 수정(#782)
- helper 알고리즘을 사용하여 명세 단계 단순화(#737)
- 유형 참조 개선(#735)
- WebIDL transferable 정의 참조(#732)
- 용어 사용 개선을 위해 산문에서 "sequence" 사용 회피(#729)
- 향상된 linting 및 검증을 위해 알고리즘 단계 검증 로직 개선(#727)
- 향상된 상호 참조를 위해 메서드 인수 정의 링크(#721)
- 구성 개선을 위해 불필요한 하위 절 제거(#711)
- 형용사 의미인 경우 "empty" 대신 "is empty"에 링크(#708)
- 이 명세의 작성 및 검토를 쉽게 하는 유틸리티 추가(#702)
- "transferred" 상호 참조 수정(#679)
- 작성 경험 개선을 위해 "generically emulated" 텍스트를 매크로로 변경(#638)
- 'backward' 및 'both' 방향에서 LSTM 에뮬레이션 오류 수정(#802)
- 'backward' 및 'both' 방향에서 GRU 에뮬레이션 오류 수정(#803)
- 분해의 오타/JS 오류 수정(#699)