浏览代码

Merge branch 'main' into release_15_mm

/release_15_branch
Ervin Teng 4 年前
当前提交
41dd16e8
共有 28 个文件被更改,包括 347 次插入73 次删除
  1. 1
      .github/workflows/pre-commit.yml
  2. 7
      .pre-commit-config.yaml
  3. 1
      .yamato/com.unity.ml-agents-test.yml
  4. 2
      Project/Packages/manifest.json
  5. 26
      com.unity.ml-agents/CHANGELOG.md
  6. 12
      com.unity.ml-agents/CONTRIBUTING.md
  7. 28
      com.unity.ml-agents/Runtime/Analytics/InferenceAnalytics.cs
  8. 38
      com.unity.ml-agents/Runtime/Analytics/TrainingAnalytics.cs
  9. 6
      com.unity.ml-agents/Runtime/Communicator/GrpcExtensions.cs
  10. 4
      com.unity.ml-agents/Runtime/Communicator/RpcCommunicator.cs
  11. 3
      com.unity.ml-agents/Runtime/Policies/RemotePolicy.cs
  12. 9
      com.unity.ml-agents/Runtime/Unity.ML-Agents.asmdef
  13. 3
      com.unity.ml-agents/Tests/Editor/Analytics/InferenceAnalyticsTests.cs
  14. 6
      com.unity.ml-agents/Tests/Editor/Communicator/GrpcExtensionsTests.cs
  15. 7
      com.unity.ml-agents/Tests/Editor/Unity.ML-Agents.Editor.Tests.asmdef
  16. 3
      com.unity.ml-agents/package.json
  17. 4
      docs/Installation-Anaconda-Windows.md
  18. 2
      docs/Installation.md
  19. 2
      docs/Training-on-Microsoft-Azure.md
  20. 2
      gym-unity/gym_unity/__init__.py
  21. 2
      ml-agents-envs/README.md
  22. 2
      ml-agents-envs/mlagents_envs/__init__.py
  23. 2
      ml-agents/README.md
  24. 2
      ml-agents/mlagents/trainers/__init__.py
  25. 37
      .yamato/com.unity.ml-agents-optional-dep-tests.yml
  26. 52
      ml-agents/mlagents/trainers/tests/torch/test_conditioning.py
  27. 133
      ml-agents/mlagents/trainers/torch/conditioning.py
  28. 24
      utils/run_dotnet_format.py

1
.github/workflows/pre-commit.yml


- uses: actions/setup-dotnet@v1
with:
dotnet-version: '3.1.x'
- run: dotnet tool install -g dotnet-format --version 4.1.131201
- uses: pre-commit/action@v2.0.0
markdown-link-check:

7
.pre-commit-config.yaml


types: [markdown]
exclude: ".*localized.*"
- repo: https://github.com/dotnet/format
rev: "7e343070a0355c86f72bdee226b5e19ffcbac931" # TODO - update to a tagged version when one that includes the hook is ready.
hooks:
- id: dotnet-format
args: [--folder, --include]
# "Local" hooks, see https://pre-commit.com/#repository-local-hooks
- repo: local
hooks:

name: validate release links
language: script
entry: utils/validate_release_links.py

1
.yamato/com.unity.ml-agents-test.yml


{% endfor %}
{% endfor %}
{% endfor %}

2
Project/Packages/manifest.json


{
"dependencies": {
"com.unity.ads": "2.0.8",
"com.unity.analytics": "3.2.3",
"com.unity.purchasing": "2.2.1",
"com.unity.textmeshpro": "1.4.1",
"com.unity.modules.ai": "1.0.0",
"com.unity.modules.animation": "1.0.0",

26
com.unity.ml-agents/CHANGELOG.md


and this project adheres to
[Semantic Versioning](http://semver.org/spec/v2.0.0.html).
# Changelog
All notable changes to this package will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to
[Semantic Versioning](http://semver.org/spec/v2.0.0.html).
## [Unreleased]
### Major Changes
#### com.unity.ml-agents (C#)
#### ml-agents / ml-agents-envs / gym-unity (Python)
### Minor Changes
#### com.unity.ml-agents / com.unity.ml-agents.extensions (C#)
- Make com.unity.modules.unityanalytics an optional dependency. (#5109)
#### ml-agents / ml-agents-envs / gym-unity (Python)
### Bug Fixes
#### com.unity.ml-agents / com.unity.ml-agents.extensions (C#)
#### ml-agents / ml-agents-envs / gym-unity (Python)
### Major Changes
#### com.unity.ml-agents (C#)
- Make com.unity.modules.unityanalytics an optional dependency. (#5109)
## [1.9.0-preview] - 2021-03-17
### Major Changes
#### com.unity.ml-agents (C#)

12
com.unity.ml-agents/CONTRIBUTING.md


Several static checks are run on the codebase using the
[pre-commit framework](https://pre-commit.com/) during CI. To execute the same
checks locally, run `pip install pre-commit` and then `pre-commit run --all-files`.
checks locally, run:
```bash
pip install pre-commit>=2.8.0
pip install identify>==2.1.3
pre-commit run --all-files
```
Some hooks (for example, `black`) will output the corrected version of the code;
others (like `mypy`) may require more effort to fix. You can optionally run
`pre-commit install` to install it as a git hook; after this it will run on all

[`black`](https://github.com/psf/black).
C# code is formatted using [`dotnet-format`](https://github.com/dotnet/format).
You must have [dotnet](https://dotnet.microsoft.com/download) and
`dotnet-format` installed first.
You must have [dotnet](https://dotnet.microsoft.com/download) installed first
(but don't need to install `dotnet-format` - `pre-commit` will do that for you).
### Python type annotations

28
com.unity.ml-agents/Runtime/Analytics/InferenceAnalytics.cs


#if MLA_UNITY_ANALYTICS_MODULE || !UNITY_2019_4_OR_NEWER
#define MLA_UNITY_ANALYTICS_MODULE_ENABLED
#endif
using System.Diagnostics;
using Unity.Barracuda;
using Unity.MLAgents.Actuators;
using Unity.MLAgents.Inference;

#if MLA_UNITY_ANALYTICS_MODULE_ENABLED
#endif
#if MLA_UNITY_ANALYTICS_MODULE_ENABLED
#endif
#endif // MLA_UNITY_ANALYTICS_MODULE_ENABLED
#endif // UNITY_EDITOR
namespace Unity.MLAgents.Analytics

return true;
}
#if UNITY_EDITOR
#if UNITY_EDITOR && MLA_UNITY_ANALYTICS_MODULE_ENABLED
#else
if (result == AnalyticsResult.Ok)
{
s_EventRegistered = true;
}
#elif MLA_UNITY_ANALYTICS_MODULE_ENABLED
#endif
#endif
if (s_EventRegistered && s_SentModels == null)
{
s_SentModels = new HashSet<NNModel>();

/// <param name="actionSpec">ActionSpec for the Agent. Used to generate information about the action space.</param>
/// <param name="actuators">List of IActuators for the Agent. Used to generate information about the action space.</param>
/// <returns></returns>
[Conditional("MLA_UNITY_ANALYTICS_MODULE_ENABLED")]
public static void InferenceModelSet(
NNModel nnModel,
string behaviorName,

var data = GetEventForModel(nnModel, behaviorName, inferenceDevice, sensors, actionSpec, actuators);
// Note - to debug, use JsonUtility.ToJson on the event.
// Debug.Log(JsonUtility.ToJson(data, true));
#if UNITY_EDITOR
#if UNITY_EDITOR && MLA_UNITY_ANALYTICS_MODULE_ENABLED
if (AnalyticsUtils.s_SendEditorAnalytics)
{
EditorAnalytics.SendEventWithLimit(k_EventName, data, k_EventVersion);

38
com.unity.ml-agents/Runtime/Analytics/TrainingAnalytics.cs


#if MLA_UNITY_ANALYTICS_MODULE || !UNITY_2019_4_OR_NEWER
#define MLA_UNITY_ANALYTICS_MODULE_ENABLED
#endif
using System.Diagnostics;
#if MLA_UNITY_ANALYTICS_MODULE_ENABLED
#if UNITY_EDITOR
using UnityEditor.Analytics;
#endif
#endif
using UnityEditor.Analytics;
#endif
namespace Unity.MLAgents.Analytics

static bool EnableAnalytics()
{
#if MLA_UNITY_ANALYTICS_MODULE_ENABLED
#else
AnalyticsResult result = AnalyticsResult.UnsupportedPlatform;
#endif
#else
return false;
#endif // UNITY_EDITOR
}
s_EventsRegistered = true;

}
return s_EventsRegistered;
#else
return false;
#endif // MLA_UNITY_ANALYTICS_MODULE_ENABLED
}
/// <summary>

/// <param name="packageVersion"></param>
[Conditional("MLA_UNITY_ANALYTICS_MODULE_ENABLED")]
public static void SetTrainerInformation(string packageVersion, string communicationVersion)
{
s_TrainerPackageVersion = packageVersion;

public static bool IsAnalyticsEnabled()
{
#if UNITY_EDITOR
#if UNITY_EDITOR && MLA_UNITY_ANALYTICS_MODULE_ENABLED
return EditorAnalytics.enabled;
#else
return false;

[Conditional("MLA_UNITY_ANALYTICS_MODULE_ENABLED")]
public static void TrainingEnvironmentInitialized(TrainingEnvironmentInitializedEvent tbiEvent)
{
if (!IsAnalyticsEnabled())

// Debug.Log(
// $"Would send event {k_TrainingEnvironmentInitializedEventName} with body {JsonUtility.ToJson(tbiEvent, true)}"
// );
#if UNITY_EDITOR
#if UNITY_EDITOR && MLA_UNITY_ANALYTICS_MODULE_ENABLED
#else
return;
[Conditional("MLA_UNITY_ANALYTICS_MODULE_ENABLED")]
public static void RemotePolicyInitialized(
string fullyQualifiedBehaviorName,
IList<ISensor> sensors,

// Debug.Log(
// $"Would send event {k_RemotePolicyInitializedEventName} with body {JsonUtility.ToJson(data, true)}"
// );
#if UNITY_EDITOR
#if UNITY_EDITOR && MLA_UNITY_ANALYTICS_MODULE_ENABLED
#else
return;
#endif
}

return fullyQualifiedBehaviorName.Substring(0, lastQuestionIndex);
}
[Conditional("MLA_UNITY_ANALYTICS_MODULE_ENABLED")]
public static void TrainingBehaviorInitialized(TrainingBehaviorInitializedEvent tbiEvent)
{
if (!IsAnalyticsEnabled())

// Debug.Log(
// $"Would send event {k_TrainingBehaviorInitializedEventName} with body {JsonUtility.ToJson(tbiEvent, true)}"
// );
#if UNITY_EDITOR
#if UNITY_EDITOR && MLA_UNITY_ANALYTICS_MODULE_ENABLED
if (AnalyticsUtils.s_SendEditorAnalytics)
{
EditorAnalytics.SendEventWithLimit(k_TrainingBehaviorInitializedEventName, tbiEvent);

6
com.unity.ml-agents/Runtime/Communicator/GrpcExtensions.cs


using UnityEngine;
using System.Runtime.CompilerServices;
using Unity.MLAgents.Actuators;
using Unity.MLAgents.Analytics;
using Unity.MLAgents.Analytics;
[assembly: InternalsVisibleTo("Unity.ML-Agents.Editor")]
[assembly: InternalsVisibleTo("Unity.ML-Agents.Editor.Tests")]

/// <returns>The protobuf version of the AgentInfo.</returns>
public static AgentInfoProto ToAgentInfoProto(this AgentInfo ai)
{
if(ai.groupId > 0)
if (ai.groupId > 0)
{
var trainerCanHandle = Academy.Instance.TrainerCapabilities == null || Academy.Instance.TrainerCapabilities.MultiAgentGroups;
if (!trainerCanHandle)

}
#region Analytics
internal static TrainingEnvironmentInitializedEvent ToTrainingEnvironmentInitializedEvent(
this TrainingEnvironmentInitialized inputProto)
{

NumNetworkHiddenUnits = inputProto.NumNetworkHiddenUnits,
};
}
#endregion
}

4
com.unity.ml-agents/Runtime/Communicator/RpcCommunicator.cs


using System.Linq;
using UnityEngine;
using Unity.MLAgents.Actuators;
using Unity.MLAgents.Analytics;
using Unity.MLAgents.Analytics;
namespace Unity.MLAgents
{

var pythonPackageVersion = initializationInput.RlInitializationInput.PackageVersion;
var pythonCommunicationVersion = initializationInput.RlInitializationInput.CommunicationVersion;
TrainingAnalytics.SetTrainerInformation(pythonPackageVersion, pythonCommunicationVersion);
var communicationIsCompatible = CheckCommunicationVersionsAreCompatible(

3
com.unity.ml-agents/Runtime/Policies/RemotePolicy.cs


using Unity.MLAgents.Sensors;
using Unity.MLAgents.Sensors;
namespace Unity.MLAgents.Policies

9
com.unity.ml-agents/Runtime/Unity.ML-Agents.asmdef


"Grpc.Core.dll"
],
"autoReferenced": true,
"defineConstraints": []
"defineConstraints": [],
"versionDefines": [
{
"name": "com.unity.modules.unityanalytics",
"expression": "1.0.0",
"define": "MLA_UNITY_ANALYTICS_MODULE"
}
]
}

3
com.unity.ml-agents/Tests/Editor/Analytics/InferenceAnalyticsTests.cs


using UnityEngine;
using Unity.Barracuda;
using Unity.MLAgents.Actuators;
using Unity.MLAgents.Analytics;
using Unity.MLAgents.Analytics;
namespace Unity.MLAgents.Tests.Analytics
{

6
com.unity.ml-agents/Tests/Editor/Communicator/GrpcExtensionsTests.cs


using NUnit.Framework;
using Unity.MLAgents.Actuators;
using Unity.MLAgents.Analytics;
using Unity.MLAgents.CommunicatorObjects;
using Unity.MLAgents.Analytics;
using Unity.MLAgents.CommunicatorObjects;
namespace Unity.MLAgents.Tests
{

sparseChannelSensor.Mapping = new[] { 0, 0, 0, 1, 1, 1 };
Assert.AreEqual(GrpcExtensions.IsTrivialMapping(sparseChannelSensor), false);
}
[Test]
public void TestDefaultTrainingEvents()
{

7
com.unity.ml-agents/Tests/Editor/Unity.ML-Agents.Editor.Tests.asmdef


"autoReferenced": false,
"defineConstraints": [
"UNITY_INCLUDE_TESTS"
],
"versionDefines": [
{
"name": "com.unity.modules.unityanalytics",
"expression": "1.0.0",
"define": "MLA_UNITY_ANALYTICS_MODULE"
}
]
}

3
com.unity.ml-agents/package.json


"com.unity.modules.imageconversion": "1.0.0",
"com.unity.modules.jsonserialize": "1.0.0",
"com.unity.modules.physics": "1.0.0",
"com.unity.modules.physics2d": "1.0.0",
"com.unity.modules.unityanalytics": "1.0.0"
"com.unity.modules.physics2d": "1.0.0"
}
}

4
docs/Installation-Anaconda-Windows.md


connected to the Internet and then type in the Anaconda Prompt:
```console
python -m pip install mlagents==0.25.0
python -m pip install mlagents==0.26.0.dev0
```
This will complete the installation of all the required Python packages to run

this, you can try:
```console
python -m pip install mlagents==0.25.0 --no-cache-dir
python -m pip install mlagents==0.26.0.dev0 --no-cache-dir
```
This `--no-cache-dir` tells the pip to disable the cache.

2
docs/Installation.md


run from the command line:
```sh
python -m pip install mlagents==0.25.0
python -m pip install mlagents==0.26.0.dev0
```
Note that this will install `mlagents` from PyPi, _not_ from the cloned

2
docs/Training-on-Microsoft-Azure.md


instance, and set it as the working directory.
2. Install the required packages:
Torch: `pip3 install torch==1.7.0 -f https://download.pytorch.org/whl/torch_stable.html` and
MLAgents: `python -m pip install mlagents==0.25.0`
MLAgents: `python -m pip install mlagents==0.26.0.dev0`
## Testing

2
gym-unity/gym_unity/__init__.py


# Version of the library that will be used to upload to pypi
__version__ = "0.25.0"
__version__ = "0.26.0.dev0"
# Git tag that will be checked to determine whether to trigger upload to pypi
__release_tag__ = "release_15"

2
ml-agents-envs/README.md


Install the `mlagents_envs` package with:
```sh
python -m pip install mlagents_envs==0.25.0
python -m pip install mlagents_envs==0.26.0.dev0
```
## Usage & More Information

2
ml-agents-envs/mlagents_envs/__init__.py


# Version of the library that will be used to upload to pypi
__version__ = "0.25.0"
__version__ = "0.26.0.dev0"
# Git tag that will be checked to determine whether to trigger upload to pypi
__release_tag__ = "release_15"

2
ml-agents/README.md


Install the `mlagents` package with:
```sh
python -m pip install mlagents==0.25.0
python -m pip install mlagents==0.26.0.dev0
```
## Usage & More Information

2
ml-agents/mlagents/trainers/__init__.py


# Version of the library that will be used to upload to pypi
__version__ = "0.25.0"
__version__ = "0.26.0.dev0"
# Git tag that will be checked to determine whether to trigger upload to pypi
__release_tag__ = "release_15"

37
.yamato/com.unity.ml-agents-optional-dep-tests.yml


OptionalDependencyTestsLinux:
name : LinuxOptionalDependenciesTests
agent:
type: Unity::VM
image: package-ci/ubuntu:stable
flavor: b1.medium
commands:
- |
curl -L https://artifactory.prd.it.unity3d.com/artifactory/api/gpg/key/public | sudo apt-key add -
sudo sh -c "echo 'deb https://artifactory.prd.it.unity3d.com/artifactory/unity-apt-local bionic main' > /etc/apt/sources.list.d/unity.list"
sudo apt update
sudo apt install -y unity-config
npm install upm-ci-utils@stable -g --registry https://artifactory.prd.cds.internal.unity3d.com/artifactory/api/npm/upm-npm
unity-config settings editor-path ./.Editor
unity-config project create opt-deps-test
unity-config project add dependency com.unity.ml-agents/
unity-config project add testable com.unity.ml-agents
unity-config project add dependency com.unity.modules.imageconversion@1.0.0
unity-config project add dependency com.unity.modules.jsonserialize@1.0.0
unity-config project add dependency com.unity.modules.physics@1.0.0
unity-config project add dependency com.unity.modules.physics2d@1.0.0
upm-ci project test -u 2019.4 --type project-tests --project-path opt-deps-test --package-filter com.unity.ml-agents
artifacts:
logs:
paths:
- "upm-ci~/test-results/**/*"
dependencies:
- .yamato/com.unity.ml-agents-pack.yml#pack
triggers:
cancel_old_ci: true
expression: |
(pull_request.target eq "main" OR
pull_request.target match "release.+") AND
NOT pull_request.draft AND
(pull_request.changes.any match "com.unity.ml-agents/**" OR
pull_request.changes.any match ".yamato/com.unity.ml-agents-test.yml")

52
ml-agents/mlagents/trainers/tests/torch/test_conditioning.py


import pytest
from mlagents.torch_utils import torch
import numpy as np
from mlagents.trainers.torch.layers import linear_layer
from mlagents.trainers.torch.conditioning import ConditionalEncoder
def test_conditional_layer_initialization():
b, input_size, goal_size, h, num_cond_layers, num_normal_layers = 7, 10, 8, 16, 2, 1
conditional_enc = ConditionalEncoder(
input_size, goal_size, h, num_normal_layers + num_cond_layers, num_cond_layers
)
input_tensor = torch.ones(b, input_size)
goal_tensor = torch.ones(b, goal_size)
output = conditional_enc.forward(input_tensor, goal_tensor)
assert output.shape == (b, h)
@pytest.mark.parametrize("num_cond_layers", [1, 2, 3])
def test_predict_with_condition(num_cond_layers):
np.random.seed(1336)
torch.manual_seed(1336)
input_size, goal_size, h, num_normal_layers = 10, 1, 16, 1
conditional_enc = ConditionalEncoder(
input_size, goal_size, h, num_normal_layers + num_cond_layers, num_cond_layers
)
l_layer = linear_layer(h, 1)
optimizer = torch.optim.Adam(
list(conditional_enc.parameters()) + list(l_layer.parameters()), lr=0.001
)
batch_size = 200
for _ in range(300):
input_tensor = torch.rand((batch_size, input_size))
goal_tensor = (torch.rand((batch_size, goal_size)) > 0.5).float()
# If the goal is 1: do the sum of the inputs, else, return 0
target = torch.sum(input_tensor, dim=1, keepdim=True) * goal_tensor
target.detach()
prediction = l_layer(conditional_enc(input_tensor, goal_tensor))
error = torch.mean((prediction - target) ** 2, dim=1)
error = torch.mean(error) / 2
print(error.item())
optimizer.zero_grad()
error.backward()
optimizer.step()
assert error.item() < 0.02

133
ml-agents/mlagents/trainers/torch/conditioning.py


from mlagents.torch_utils import torch
from typing import List
import math
from mlagents.trainers.torch.layers import (
linear_layer,
Swish,
Initialization,
LayerNorm,
)
class ConditionalEncoder(torch.nn.Module):
def __init__(
self,
input_size: int,
goal_size: int,
hidden_size: int,
num_layers: int,
num_conditional_layers: int,
kernel_init: Initialization = Initialization.KaimingHeNormal,
kernel_gain: float = 1.0,
):
"""
ConditionalEncoder module. A fully connected network of which some of the
weights are generated by a goal conditioning. Uses the HyperNetwork module to
generate the weights of the network. Only the weights of the last
"num_conditional_layers" layers will be generated by HyperNetworks, the others
will use regular parameters.
:param input_size: The size of the input of the encoder
:param goal_size: The size of the goal tensor that will condition the encoder
:param hidden_size: The number of hidden units in the encoder
:param num_layers: The total number of layers of the encoder (both regular and
generated by HyperNetwork)
:param num_conditional_layers: The number of layers generated with hypernetworks
:param kernel_init: The Initialization to use for the weights of the layer
:param kernel_gain: The multiplier for the weights of the kernel.
"""
super().__init__()
layers: List[torch.nn.Module] = []
prev_size = input_size + goal_size
for i in range(num_layers):
if num_layers - i <= num_conditional_layers:
# This means layer i is a conditional layer since the conditional
# leyers are the last num_conditional_layers
layers.append(
HyperNetwork(prev_size, hidden_size, goal_size, hidden_size, 2)
)
else:
layers.append(
linear_layer(
prev_size,
hidden_size,
kernel_init=kernel_init,
kernel_gain=kernel_gain,
)
)
layers.append(Swish())
prev_size = hidden_size
self.layers = torch.nn.ModuleList(layers)
def forward(
self, input_tensor: torch.Tensor, goal_tensor: torch.Tensor
) -> torch.Tensor: # type: ignore
activation = torch.cat([input_tensor, goal_tensor], dim=-1)
for layer in self.layers:
if isinstance(layer, HyperNetwork):
activation = layer(activation, goal_tensor)
else:
activation = layer(activation)
return activation
class HyperNetwork(torch.nn.Module):
def __init__(
self, input_size, output_size, hyper_input_size, layer_size, num_layers
):
"""
Hyper Network module. This module will use the hyper_input tensor to generate
the weights of the main network. The main network is a single fully connected
layer.
:param input_size: The size of the input of the main network
:param output_size: The size of the output of the main network
:param hyper_input_size: The size of the input of the hypernetwork that will
generate the main network.
:param layer_size: The number of hidden units in the layers of the hypernetwork
:param num_layers: The number of layers of the hypernetwork
"""
super().__init__()
self.input_size = input_size
self.output_size = output_size
layer_in_size = hyper_input_size
layers = []
for _ in range(num_layers):
layers.append(
linear_layer(
layer_in_size,
layer_size,
kernel_init=Initialization.KaimingHeNormal,
kernel_gain=1.0,
bias_init=Initialization.Zero,
)
)
layers.append(Swish())
layer_in_size = layer_size
flat_output = linear_layer(
layer_size,
input_size * output_size,
kernel_init=Initialization.KaimingHeNormal,
kernel_gain=0.1,
bias_init=Initialization.Zero,
)
# Re-initializing the weights of the last layer of the hypernetwork
bound = math.sqrt(1 / (layer_size * self.input_size))
flat_output.weight.data.uniform_(-bound, bound)
self.hypernet = torch.nn.Sequential(*layers, LayerNorm(), flat_output)
# The hypernetwork will not generate the bias of the main network layer
self.bias = torch.nn.Parameter(torch.zeros(output_size))
def forward(self, input_activation, hyper_input):
output_weights = self.hypernet(hyper_input)
output_weights = output_weights.view(-1, self.input_size, self.output_size)
result = (
torch.bmm(input_activation.unsqueeze(1), output_weights).squeeze(1)
+ self.bias
)
return result

24
utils/run_dotnet_format.py


#!/usr/bin/env python3
import argparse
import os
import subprocess
import tempfile
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("files", nargs="*")
args = parser.parse_args()
with tempfile.TemporaryDirectory() as tempdir:
# Could potentially hit the commandline limit, so write files to a response file
# See https://github.com/dotnet/format/issues/699
resp_file = os.path.join(tempdir, "response.txt")
with open(resp_file, "w") as fp:
for f in args.files:
fp.write(f + "\n")
subprocess_args = ["dotnet", "format", "--folder", "--include", f"@{resp_file}"]
subprocess.check_call(subprocess_args)
正在加载...
取消
保存