in unity's ML Agents do I need to modify my PlayerController which works with player…
- User
in unity's ML Agents do I need to modify my PlayerController which works with player input? or do I need to create a new script and make references in the code to each other?
- Assistant
In Unity's ML Agents, you typically create a new script called "AgentScript" that inherits from the "Agent" class provided by the ML-Agents API. You don't have to modify your existing PlayerController script.
Here are the steps to create an agent:
-
Create a new script called "AgentScript" and open it in the editor.
-
Replace the "MonoBehaviour" class inheritance with the "Agent" class provided by ML-Agents.
-
Override the necessary methods which are used to define agent behavior:
-
- User
- Assistant
Here's an AgentScript that you can use with your PlayerController. This agent will simply move and shoot randomly during the training.
using UnityEngine; using Unity.MLAgents; using Unity.MLAgents.Sensors; using Unity.MLAgents.Actuators; public class MyAgent : Agent { public PlayerController playerController; public override void OnEpisodeBegin() { // Reset player position, health, or any other variables here } public override void CollectObservations(VectorSensor sensor) { // Call the CollectObservations method from PlayerController to add observations playerController.CollectObservations(sensor); } public override void OnActionReceived(float[] vectorAction) { // Move the player using the first two elements of the action array as horizontal and vertical input playerController.ControlJoystick(vectorAction[0], vectorAction[1]); // Shoot if the third element of the action array is greater than 0 if (vectorAction[2] > 0) { playerController.Shoot(Mathf.Atan2(vectorAction[0], vectorAction[1])); } // You can also provide rewards or penalties depending on the agent's performance // AddReward(0.1f); // Example reward // AddReward(-0.1f); // Example penalty } public override void Heuristic(float[] actionsOut) { // Implement manual control for testing actionsOut[0] = Input.GetAxis("Horizontal"); actionsOut[1] = Input.GetAxis("Vertical"); actionsOut[2] = Input.GetMouseButton(0) ? 1f : 0f; } } - User
I did everything as you said, in the Behavior Name I specified MyPlayerAgent. I write a command to the console, press Play in Unity, it seems to connect to each other, but my agent does nothing, as if the console cannot find the agent, then after a while the console gives an error about a long wait.
here's my playerAgent_config.yaml: behaviors: MyPlayerAgent: trainer_type: ppo hyperparameters: batch_size: 1024 buffer_size: 10240 learning_rate: 3.0e-4 beta: 5.0e-3 epsilon: 0.2 lambd: 0.95 num_epoch: 3 learning_rate_schedule: linear network_settings: normalize: false hidden_units: 128 num_layers: 2 vis_encode_type: simple memory: memory_size: 256 sequence_length: 64 reward_signals: extrinsic: gamma: 0.99 strength: 1.0 keep_checkpoints: 5 max_steps: 5.0e4 time_horizon: 64 summary_freq: 10000
(mlagents) C:\Projects\Unity\ml-agents-release_20>mlagents-learn playerAgent_config.yaml --run-id=player_agent_001 --force Version information: ml-agents: 0.30.0, ml-agents-envs: 0.30.0, Communicator API: 1.5.0, PyTorch: 2.0.1+cu117 [INFO] Listening on port 5004. Start training by pressing the Play button in the Unity Editor. [INFO] Connected to Unity environment with package version 2.3.0-exp.3 and communication version 1.5.0
- Assistant
Based on your description, it seems that the ML-Agents environment in the Unity Editor is not correctly set up. Here are some steps to set up the environment correctly:
-
If you haven't already, import the
ML-Agents Packageinto your Unity Project. You can do this by following the instructions here. -
Create an empty GameObject in your scene and name it "MLAgentsEnvironment".
-
Attach the
SimpleMultiAgentGroupandBehavior Parameterscomponents to the "MLAgentsEnvironment" game object. -
Make sure the "Behavior Name" in the Behavior Parameters matches the name specified in your playerAgent_config.yaml file (In this case, it should be "MyPlayerAgent").
-
- User
everything is done as you wrote, but functions like Heuristic and OnActionReceived are not called. In the Unity console only: Registered Communicator in Agent. UnityEngine.Debug:Log (object) Unity.MLAgents.Agent:Awake() (at C:/Projects/Unity/ml-agents-release_20/com.unity.ml-agents/Runtime/Agent.cs:373)
- Assistant
It looks like there is a communication issue between the Unity environment and the ML-Agents learning process. Please follow these steps to make sure the communication is appropriately set up:
-
In your Unity Project, open the
ProjectSettingswindow by clickingEdit -> Project Settings. -
Navigate to the
Playersettings tab and select the appropriate platform for your project (e.g., PC, Mac & Linux Standalone). -
Scroll down to the
Configurationsection and set theScripting Define Symbolsto include "MLAPI_EDITOR_EXTENSIONS;ENABLE_NN_API". Press enter to apply the change. -
Close the
ProjectSettingswindow and save your scene. Restart the Unity Editor to apply the changes.
Once the Scripting Define Symbols are set up, run the training command again and press the Play button in the Unity Editor. Your agent should start training and
HeuristicandOnActionReceivedmethods should be called.If the issue persists, please share a screenshot of your Unity scene setup (Hierarchy and Inspector), and I can help you debug further.
-
- User
I added a Decision Requester and some actions started in the code. I got a line in the terminal "[INFO] Connected new brain: MyPlayerAgent?team=0". then a copy of my yaml file, but the training did not start, after some time I got an error:
[WARNING] Restarting worker[0] after 'The Unity environment took too long to respond. Make sure that: The environment does not need user interaction to launch The Agents' Behavior Parameters > Behavior Type is set to "Default" The environment and the Python interface have compatible versions. If you're running on a headless server without graphics support, turn off display by either passing --no-graphics option or build your Unity executable as server build.'
- Assistant
Adding a
Decision Requestershould indeed help in regular decision-making calls, which is necessary for the agent's training. I apologize for not mentioning it in my previous response.Regarding the warning you're encountering, there are some possible causes for it:
-
In the
Behavior Parameterscomponent of your agent in Unity, ensure that theBehavior Typefield is set to "Default." -
If you're running the Unity environment and the ML-Agents training process in the same machine, you may be experiencing performance issues. To solve this, try closing any unnecessary applications or processes running on your machine.
-
If you're using a headless server without graphics support, you can pass the
--no-graphicsflag to your training command:
mlagents-learn playerAgent_config.yaml --run-id=player_agent_001 --force --no-graphicsor build your Unity executable as a server build.
- If none of the above solutions work, try decreasing the
Decision Periodvalue in the component. This value tells the Agent how often to request a decision, and decreasing it might help the agent make decisions more frequently.
-
- User
when i start training i get error in terminal: RuntimeError: mat1 and mat2 shapes cannot be multiplied (1x4 and 3x128)
here's my BasicAgent.cs: using UnityEngine; using Unity.MLAgents; using Unity.MLAgents.Sensors; using Unity.MLAgents.Actuators;
public class BasicAgent : Agent { public PlayerController playerController;
public override void OnEpisodeBegin() { Debug.Log("Episode Begin"); } public override void CollectObservations(VectorSensor sensor) { Debug.Log("Collect Observations"); // Target and Agent positions sensor.AddObservation(1); sensor.AddObservation(2); // Agent velocity sensor.AddObservation(3); sensor.AddObservation(4); } public override void OnActionReceived(ActionBuffers actionBuffers) { Debug.Log("On Action Received"); SetReward(1.0f); EndEpisode(); } public override void Heuristic(in ActionBuffers actionsOut) { Debug.Log("Heuristic - manual mode"); var continuousActionsOut = actionsOut.ContinuousActions; continuousActionsOut[0] = Input.GetAxis("Horizontal"); continuousActionsOut[1] = Input.GetAxis("Vertical"); }}
- Assistant
The error you're encountering is related to the size of the input vector, which doesn't match the size expected by your neural network model. To solve this, ensure that the observation space in your agent matches the size specified in the neural network architecture. Currently, you're adding four observations, leading to an input size of 4. However, the model seems to be expecting an input size of 3.
To fix this issue, you can either add or remove observations in the
CollectObservationsmethod. For example, you can remove the last observation to have an input vector of size 3:public override void CollectObservations(VectorSensor sensor) { Debug.Log("Collect Observations"); // Target and Agent positions sensor.AddObservation(1); sensor.AddObservation(2); // Agent velocity sensor.AddObservation(3); }Or, you can define a new neural network model compatible with an input size of 4.
If you have modified the neural network architecture in the
playerAgent_config.yamlfile, please share itsnetwork_settingsfor better guidance.Once you've made these changes, retry the training process, and please let me know if the issue persists.
- User
- Assistant
Based on the error message, it seems that there is still a mismatch between the observation space and the neural network architecture.
Please try specifying the network settings in your playerAgent_config.yaml. Set the
vector_observation_sizeto 3, the same size as the observation vector in theCollectObservationsmethod. Here is the updated network_settings section for your yaml file:network_settings: vector_observation_size: 3 normalize: false hidden_units: 128 num_layers: 2 vis_encode_type: simple memory: memory_size: 256 sequence_length: 64After updating the yaml file, run the training command again and press the Play button in the Unity Editor. Your agent should start training without any errors.
If the issue persists, please share the full playerAgent_config.yaml file, and I will help you debug further.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.