Harley-ml commited on
Commit
6398b33
·
verified ·
1 Parent(s): c3eb8bd

Upload 4 files

Browse files
Files changed (4) hide show
  1. config.json +19 -0
  2. configuration_mr_pong.py +39 -0
  3. model.safetensors +3 -0
  4. modeling_mr_pong.py +109 -0
config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "MrPongForRL"
4
+ ],
5
+ "model_type": "mr_pong",
6
+ "obs_dim": 12,
7
+ "action_dim": 3,
8
+ "hidden_dims": [
9
+ 160,
10
+ 160
11
+ ],
12
+ "activation": "tanh",
13
+ "torch_dtype": "float32",
14
+ "global_step": 9975808,
15
+ "auto_map": {
16
+ "AutoConfig": "configuration_mrs_paleta.MrPongConfig",
17
+ "AutoModel": "modeling_mr_pong.MrPongForRL"
18
+ }
19
+ }
configuration_mr_pong.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Configuration class for Mrs. Paleta Ping Pong RL Agent.
3
+ """
4
+
5
+ from transformers import PretrainedConfig
6
+
7
+
8
+ class MrPongConfig(PretrainedConfig):
9
+ model_type = "mrs_paleta"
10
+
11
+ def __init__(
12
+ self,
13
+ obs_dim: int = 12,
14
+ action_dim: int = 3,
15
+ hidden_dims: list = None,
16
+ activation: str = "tanh",
17
+ table_width: float = 800.0,
18
+ table_height: float = 500.0,
19
+ paddle_width: float = 14.0,
20
+ paddle_height: float = 80.0,
21
+ paddle_speed: float = 8.0,
22
+ ball_speed_max: float = 16.0,
23
+ max_rally_steps: int = 1500,
24
+ **kwargs
25
+ ):
26
+ if hidden_dims is None:
27
+ hidden_dims = [160, 160]
28
+ self.obs_dim = obs_dim
29
+ self.action_dim = action_dim
30
+ self.hidden_dims = hidden_dims
31
+ self.activation = activation
32
+ self.table_width = table_width
33
+ self.table_height = table_height
34
+ self.paddle_width = paddle_width
35
+ self.paddle_height = paddle_height
36
+ self.paddle_speed = paddle_speed
37
+ self.ball_speed_max = ball_speed_max
38
+ self.max_rally_steps = max_rally_steps
39
+ super().__init__(**kwargs)
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5dae8d682e24a85661abd97f1d6ba09602aea5e395c91a78f9cdb1844ca8d161
3
+ size 114536
modeling_mr_pong.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ PyTorch Modeling class for Mrs. Paleta Ping Pong RL Agent.
3
+ Compatible with Hugging Face AutoModel via trust_remote_code=True.
4
+ """
5
+
6
+ from typing import Optional, Tuple, Union, Dict, Any
7
+ from dataclasses import dataclass
8
+ import numpy as np
9
+ import torch
10
+ import torch.nn as nn
11
+ from transformers import PreTrainedModel
12
+ from transformers.utils import ModelOutput
13
+
14
+ try:
15
+ from .configuration_mr_pong import MrPongConfig
16
+ except ImportError:
17
+ from configuration_mr_pong import MrPongConfig
18
+
19
+
20
+ @dataclass
21
+ class MrPongOutput(ModelOutput):
22
+ """
23
+ Model output for Mr Pong.
24
+ """
25
+ logits: torch.FloatTensor = None
26
+ value_estimate: Optional[torch.FloatTensor] = None
27
+ action: Optional[torch.LongTensor] = None
28
+
29
+
30
+ class MrPongForRL(PreTrainedModel):
31
+ config_class = MrPongConfig
32
+ base_model_prefix = "mr_pong"
33
+
34
+ def __init__(self, config: MrPongConfig):
35
+ super().__init__(config)
36
+ self.config = config
37
+
38
+ act_fn = nn.Tanh if config.activation == "tanh" else (nn.ReLU if config.activation == "relu" else nn.GELU)
39
+
40
+ layers = []
41
+ in_dim = config.obs_dim
42
+ for h_dim in config.hidden_dims:
43
+ layers.append(nn.Linear(in_dim, h_dim))
44
+ layers.append(act_fn())
45
+ in_dim = h_dim
46
+
47
+ self.trunk = nn.Sequential(*layers)
48
+ self.actor = nn.Linear(in_dim, config.action_dim)
49
+ self.critic = nn.Linear(in_dim, 1)
50
+
51
+ self.post_init()
52
+
53
+ def forward(
54
+ self,
55
+ observation: torch.FloatTensor,
56
+ deterministic: bool = True,
57
+ return_dict: Optional[bool] = None,
58
+ **kwargs
59
+ ) -> Union[Tuple[torch.FloatTensor, torch.FloatTensor], MrPongOutput]:
60
+ """
61
+ Forward pass returning action logits, state-value estimates, and greedily/sampled chosen action.
62
+ """
63
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
64
+
65
+ if not isinstance(observation, torch.Tensor):
66
+ observation = torch.tensor(observation, dtype=torch.float32)
67
+
68
+ if observation.ndim == 1:
69
+ observation = observation.unsqueeze(0)
70
+
71
+ # Slice or pad to expected input dimension
72
+ if observation.shape[-1] > self.config.obs_dim:
73
+ observation = observation[..., :self.config.obs_dim]
74
+ elif observation.shape[-1] < self.config.obs_dim:
75
+ pad_size = self.config.obs_dim - observation.shape[-1]
76
+ observation = nn.functional.pad(observation, (0, pad_size))
77
+
78
+ features = self.trunk(observation)
79
+ logits = self.actor(features)
80
+ value = self.critic(features)
81
+
82
+ if deterministic:
83
+ action = torch.argmax(logits, dim=-1)
84
+ else:
85
+ dist = torch.distributions.Categorical(logits=logits)
86
+ action = dist.sample()
87
+
88
+ if not return_dict:
89
+ return logits, value, action
90
+
91
+ return MrPongOutput(
92
+ logits=logits,
93
+ value_estimate=value,
94
+ action=action
95
+ )
96
+
97
+ @torch.no_grad()
98
+ def act(self, observation: Union[np.ndarray, list, torch.Tensor], deterministic: bool = True) -> int:
99
+ """
100
+ High-level inference method returning single integer action (0: Stay, 1: Up, 2: Down).
101
+ """
102
+ self.eval()
103
+ if not isinstance(observation, torch.Tensor):
104
+ observation = torch.tensor(observation, dtype=torch.float32, device=self.device)
105
+ else:
106
+ observation = observation.to(self.device)
107
+
108
+ out = self.forward(observation, deterministic=deterministic, return_dict=True)
109
+ return out.action.squeeze().item()