hermes-toolkit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
hermes/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ """HERMES: a toolkit for the multi-agent simulation of emergent communication and languages."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ try:
6
+ __version__ = version("hermes-toolkit")
7
+ except PackageNotFoundError: # running from a source checkout, not installed
8
+ __version__ = "0.0.0+unknown"
9
+
10
+ __all__ = ["__version__"]
hermes/agent.py ADDED
@@ -0,0 +1,49 @@
1
+ #####################################################
2
+ # #
3
+ # Agent #
4
+ # #
5
+ #####################################################
6
+
7
+ import hermes.globals
8
+ import hermes.utils
9
+ import warnings
10
+
11
+ class Agent():
12
+ """
13
+ The base class of a HERMES agent.
14
+ """
15
+
16
+ def __init__(self, configuration):
17
+ """Initialisation of agents upon creation."""
18
+ self.configuration = {**hermes.globals.EXPERIMENT_DEFAULT_CONFIGURATION, **configuration}
19
+
20
+ def prepare_for_interaction(self):
21
+ warnings.warn('No method implemented for preparing agents before interaction.')
22
+ pass
23
+
24
+ class SingleWordAgent(Agent):
25
+
26
+ def __init__(self, configuration):
27
+
28
+ self.vocabulary = []
29
+ self.used_word = None
30
+ self.invented_word = None
31
+ self.adopted_word = None
32
+
33
+ super().__init__(configuration)
34
+
35
+ def add_word(self, meaning, form=None, score=0.5):
36
+ """Add a new word to vocabulary."""
37
+
38
+ if form is None:
39
+ form = hermes.utils.make_new_form()
40
+
41
+ word = [form, meaning, score]
42
+ self.vocabulary.append(word)
43
+
44
+ return word
45
+
46
+ def prepare_for_interaction(self):
47
+ self.used_word = None
48
+ self.invented_word = None
49
+ self.adopted_word = None
hermes/alignment.py ADDED
@@ -0,0 +1,13 @@
1
+
2
+ class AlignmentStrategy():
3
+ pass
4
+
5
+ class NoAlignment(AlignmentStrategy):
6
+ """Run no alignment"""
7
+
8
+ def run_after_success(self, process, interaction, upper_bound=1.0, lower_bound=0.0):
9
+ pass
10
+
11
+ def run_after_failure(self, process, interaction, lower_bound=0.0):
12
+ pass
13
+
hermes/experiment.py ADDED
@@ -0,0 +1,158 @@
1
+ ###########################################################
2
+ # #
3
+ # Experiment #
4
+ # #
5
+ ###########################################################
6
+
7
+ import hermes.globals
8
+ import random
9
+ import matplotlib.pyplot as plt
10
+ import sys
11
+ import importlib
12
+ import numpy as np
13
+ import pickle
14
+ import alive_progress
15
+
16
+
17
+ class Experiment():
18
+ """The HERMES experiment class."""
19
+
20
+ def __init__(self, population=None, world=None, configuration={}):
21
+ """Initialize the experiment, optionally passing a population and a world object,
22
+ otherwise retrieve population_class and world_class from configuration."""
23
+
24
+ # The configuration passed to the experiment is merged with the default configuration.
25
+ self.configuration = {**hermes.globals.EXPERIMENT_DEFAULT_CONFIGURATION, **configuration}
26
+ self.phase = None
27
+
28
+ # When device is passed in experiment configuration, use it globally
29
+ if 'device' in self.configuration:
30
+ hermes.globals.DEVICE = self.configuration['device']
31
+ else:
32
+ self.configuration['device'] = hermes.globals.DEVICE
33
+
34
+ # The population is created
35
+ if population is not None:
36
+ self.population = population
37
+ class_name = type(population).__qualname__
38
+ module_name = type(population).__module__
39
+ self.configuration['population_class'] = (class_name, module_name)
40
+ else:
41
+ class_name, module_name = self.configuration['population_class']
42
+ module = importlib.import_module(module_name)
43
+ population_class = getattr(module, class_name)
44
+ self.population = population_class(self.configuration)
45
+
46
+ # The world is created
47
+ if world is not None:
48
+ self.world = world
49
+ class_name = type(world).__qualname__
50
+ module_name = type(world).__module__
51
+ self.configuration['world_class'] = (class_name, module_name)
52
+ else:
53
+ class_name, module_name = self.configuration['world_class']
54
+ module = importlib.import_module(module_name)
55
+ world_class = getattr(module, class_name)
56
+ self.world = world_class(self.configuration)
57
+
58
+ # No current interaction yet
59
+ self.current_interaction = None
60
+
61
+ # Instantiate monitors to record experiment data
62
+ self.active_monitors = {}
63
+ for (class_name, module_name) in self.configuration['monitors']:
64
+ module = importlib.import_module(module_name)
65
+ monitor_class = getattr(module, class_name)
66
+ monitor_instance = monitor_class()
67
+ self.active_monitors[class_name] = monitor_instance
68
+
69
+ if 'logger_class' in self.configuration:
70
+ class_name, module_name = self.configuration['logger_class']
71
+ module = importlib.import_module(module_name)
72
+ logger_class = getattr(module, class_name)
73
+ self.logger = logger_class(self.configuration, self.active_monitors)
74
+ else:
75
+ self.logger = None
76
+
77
+
78
+ def run_interaction(self, phase='train', verbose=False):
79
+ """ Create a new interaction, make it happen and record the outcome. """
80
+
81
+ # Set phase of experiment
82
+ self.phase = phase
83
+
84
+ # Determine interaction type and create interaction
85
+ self.current_interaction = self.create_new_interaction()
86
+
87
+ # Run actual interaction
88
+ self.current_interaction.run(phase=self.phase, verbose=verbose)
89
+
90
+ # Record outcome
91
+ for active_monitor in self.active_monitors.values():
92
+ active_monitor.record(self.current_interaction)
93
+
94
+
95
+ def create_new_interaction(self):
96
+ """Instantiate a new interaction instance, based on a type randomly chosen from the interaction_classes list specified in the configuration."""
97
+ class_name, module_name = random.choice(self.configuration['interaction_classes'])
98
+ module = importlib.import_module(module_name)
99
+ interaction_class = getattr(module, class_name)
100
+ return interaction_class(self)
101
+
102
+
103
+ def run_series(self, nr_of_interactions, show_alive_progress=True, phase='train', verbose=False):
104
+ """Run a series of interactions."""
105
+ if show_alive_progress == True:
106
+ with alive_progress.alive_bar(nr_of_interactions, force_tty=True) as bar:
107
+ for i in range(nr_of_interactions):
108
+ self.run_interaction(phase=phase, verbose = verbose)
109
+ bar()
110
+ else:
111
+ for i in range(nr_of_interactions):
112
+ if (i + 1) % 100 == 0:
113
+ print(f'Interaction {i+1}')
114
+ self.run_interaction(phase=phase, verbose=verbose)
115
+ sys.stdout.flush()
116
+
117
+ if self.logger is not None:
118
+ self.logger.save_monitors()
119
+
120
+
121
+ def plot_outcome(self):
122
+ """Plot the results of an experiment in terms of the data that the active monitors collected throughout the experiment."""
123
+ experiment_plotpoints = {}
124
+ for name, monitor in self.active_monitors.items():
125
+ if hasattr(monitor, 'line_name'):
126
+ monitor.make_plot_points(window_size=self.configuration['plot_window_size'])
127
+ experiment_plotpoints[name] = monitor.plot_points
128
+
129
+ fig, axes = plt.subplots(len(experiment_plotpoints.keys()), figsize=(5, 7), sharex=True)
130
+
131
+ if not (isinstance(axes, list) or isinstance(axes, np.ndarray)):
132
+ axes = [axes]
133
+
134
+ for i, key in enumerate(experiment_plotpoints.keys()):
135
+ ax = axes[i]
136
+
137
+ for line, points in experiment_plotpoints[key].items():
138
+ ax.plot(points.keys(), points.values(), label=line)
139
+ ax.set_title(key)
140
+ ax.grid()
141
+ ax.legend()
142
+
143
+ plt.show()
144
+
145
+ def save_population(self):
146
+ self.population.save("./xp_outputs/")
147
+
148
+ def load_population(self, path):
149
+ self.population.load(path)
150
+
151
+ def store(self, filename):
152
+ """Store experiment object under filename."""
153
+ with open(filename, 'wb') as output: # Overwrites any existing file.
154
+ pickle.dump(self, output, -1)
155
+
156
+ def flush_all_monitors(self):
157
+ for monitor in self.active_monitors.values():
158
+ monitor.flush()
hermes/globals.py ADDED
@@ -0,0 +1,51 @@
1
+ ###########################
2
+ # #
3
+ # Hermes global variables #
4
+ # #
5
+ ###########################
6
+
7
+ # Default experiment configuration
8
+ EXPERIMENT_DEFAULT_CONFIGURATION = {
9
+ 'agent_class': ('Agent', 'hermes.agent'),
10
+ 'world_class': ('EntityWorld', 'hermes.world'),
11
+ 'population_class': ('UniformPopulation', 'hermes.population'),
12
+ 'interaction_classes': [("DescribeAndPointInteraction", "hermes.interaction")],
13
+ 'monitors': [('TraceInteractionSuccess', 'hermes.monitoring')],
14
+ 'alignment_strategy': ('NoAlignment', 'hermes.alignment'),
15
+ 'population_size': 10,
16
+ 'plot_window_size': 100
17
+ }
18
+
19
+ # Torch device for GPU use.
20
+ #
21
+ # PyTorch is an optional dependency. The core framework is pure Python; only
22
+ # experiments with neurally grounded agents need torch, which is installed with
23
+ # pip install "hermes-toolkit[torch]"
24
+ # When torch is not installed, DEVICE is None and torch-based agents are
25
+ # unavailable, but the rest of the framework still imports and runs.
26
+ #
27
+ # Device selection is defensive on purpose: this runs at import time, so an
28
+ # unexpected failure here would make `import hermes` fail for everyone rather
29
+ # than fall back to CPU.
30
+
31
+ try:
32
+ import torch
33
+ except ImportError: # pragma: no cover
34
+ torch = None
35
+ DEVICE = None
36
+ else:
37
+ def _select_device():
38
+ """Return the best available torch device, falling back to CPU."""
39
+ try:
40
+ if torch.cuda.is_available():
41
+ return torch.device("cuda")
42
+ except Exception:
43
+ pass
44
+ try:
45
+ if torch.backends.mps.is_available():
46
+ return torch.device("mps")
47
+ except Exception:
48
+ pass
49
+ return torch.device("cpu")
50
+
51
+ DEVICE = _select_device()
hermes/interaction.py ADDED
@@ -0,0 +1,128 @@
1
+ ###########################################
2
+ # #
3
+ # Interaction #
4
+ # #
5
+ ###########################################
6
+
7
+ import hermes.process
8
+ import importlib
9
+ import hermes.alignment
10
+
11
+ class Interaction:
12
+ """ General interaction class. """
13
+
14
+ def __init__(self, experiment):
15
+ self.experiment = experiment
16
+ self.configuration = experiment.configuration
17
+ self.interacting_agents = []
18
+ self.succeeded = None
19
+
20
+ alignment_strategy = self.configuration['alignment_strategy']
21
+ if alignment_strategy is not None and alignment_strategy != []:
22
+ class_name, module_name = self.configuration['alignment_strategy']
23
+ module = importlib.import_module(module_name)
24
+ alignment_class = getattr(module, class_name)
25
+ self.alignment_strategy = alignment_class()
26
+ else:
27
+ self.alignment_strategy = hermes.alignment.NoAlignment()
28
+
29
+ class DescribeAndPointInteraction(Interaction):
30
+ """Interaction class for description-and-point interactions."""
31
+ def __init__(self, experiment, speaker_process_class=('DescriptionProcess', 'hermes.process'), listener_process_class=('PointingProcess', 'hermes.process')):
32
+
33
+ # Call init method of superclass
34
+ super().__init__(experiment)
35
+
36
+ self.speaker_process_class = speaker_process_class
37
+ self.listener_process_class = listener_process_class
38
+
39
+ # Select the interacting agents for the experiment, one speaker and one listener, prepare them interaction
40
+ self.select_interacting_agents()
41
+ self.speaker.prepare_for_interaction()
42
+ self.listener.prepare_for_interaction()
43
+
44
+ # Load scene
45
+ self.load_scene()
46
+
47
+ self.make_processes()
48
+
49
+ def make_processes(self):
50
+ # Set speaker process
51
+ speaker_process_class_name, speaker_process_module_name = self.speaker_process_class
52
+ speaker_process_module = importlib.import_module(speaker_process_module_name)
53
+ speaker_process_class = getattr(speaker_process_module, speaker_process_class_name)
54
+ self.speaker_process = speaker_process_class(self.speaker, self.speaker_scene, self.speaker_target, self)
55
+ self.speaker.processes = [self.speaker_process]
56
+
57
+ # Set listener process
58
+ listener_process_class_name, listener_process_module_name = self.listener_process_class
59
+ listener_process_module = importlib.import_module(listener_process_module_name)
60
+ listener_process_class = getattr(listener_process_module, listener_process_class_name)
61
+ self.listener_process = listener_process_class(self.listener, self.listener_scene, self)
62
+ self.listener.processes = [self.listener_process]
63
+
64
+ def load_scene(self):
65
+ scene, target = self.experiment.world.sample_scene_with_target(self.configuration, split=self.experiment.phase)
66
+ self.speaker_scene = scene
67
+ self.speaker_target = target # gold target
68
+ self.listener_scene = scene
69
+ self.listener_target = target # gold target
70
+
71
+ def select_interacting_agents(self):
72
+ self.interacting_agents = self.experiment.population.sample_agents(2)
73
+ self.speaker = self.interacting_agents[0]
74
+ self.listener = self.interacting_agents[1]
75
+
76
+ def run(self, phase='train', verbose=False):
77
+ """Defines the interaction script."""
78
+
79
+ # Run description task speaker:
80
+ self.speaker_process.run(phase)
81
+ spoken_utterance = self.speaker_process.utterance
82
+
83
+ # print(f'Speaker says: {spoken_utterance}')
84
+
85
+ # Run pointing task listener
86
+ self.listener_process.run(spoken_utterance)
87
+
88
+ # Determine interaction success
89
+ self.determine_communicative_success()
90
+
91
+ if verbose:
92
+ if self.succeeded == True:
93
+ print(f'Interaction succeeded!!!')
94
+ else:
95
+ print("Interaction failed...")
96
+ if hasattr(self.speaker_process.agent, "invented_word"):
97
+ if self.speaker_process.agent.invented_word is not None:
98
+ print(f'(speaker)...')
99
+ else:
100
+ print(f'(listener)...')
101
+
102
+ # Run adoption/reward policy
103
+ if phase == 'train':
104
+ self.learn()
105
+
106
+
107
+ def learn(self):
108
+ """Run the alignment strategy after success or failure, passing the speaker and listener processes.
109
+
110
+ Repair behaviour such as adopting an unknown word belongs in the
111
+ alignment strategy, not here: an `AlignmentStrategy` subclass decides
112
+ what each agent does once the outcome of the interaction is known.
113
+ """
114
+ if self.succeeded is True:
115
+ self.alignment_strategy.run_after_success(self.speaker_process, self)
116
+ self.alignment_strategy.run_after_success(self.listener_process, self)
117
+
118
+ else:
119
+ self.alignment_strategy.run_after_failure(self.speaker_process, self)
120
+ self.alignment_strategy.run_after_failure(self.listener_process, self)
121
+
122
+
123
+ def determine_communicative_success(self):
124
+ """Determine communicative success of interaction."""
125
+ if self.listener_process.hypothesised_target == self.listener_target:
126
+ self.succeeded = True
127
+ else:
128
+ self.succeeded = False
hermes/logging.py ADDED
@@ -0,0 +1,114 @@
1
+ import shutil
2
+ import json
3
+ import time
4
+ import os
5
+ import pandas as pd
6
+
7
+ from pathlib import Path
8
+
9
+
10
+ #####################################################
11
+ # #
12
+ # Utils #
13
+ # #
14
+ #####################################################
15
+
16
+ BASE_OUTPUT_DIR = './xp_outputs'
17
+ WANDB_OUTPUT_DIR = './outputs'
18
+
19
+
20
+ def make_output_dirs(cfg):
21
+ base_output_path = Path(BASE_OUTPUT_DIR)
22
+ if not base_output_path.exists():
23
+ print(f"Creating directory at '{BASE_OUTPUT_DIR}' for logging experiements.")
24
+ os.makedirs(base_output_path)
25
+
26
+ model_dir = base_output_path / cfg['xp_name']
27
+ if not model_dir.exists():
28
+ curr_run = 1
29
+ else:
30
+ # If a directory with the same xp_name exists, find the run number of the new xp by looking at existing run folders
31
+ exst_run_nums = [
32
+ int(str(folder.name).split('run')[1])
33
+ for folder in model_dir.iterdir()
34
+ if str(folder.name).startswith('run')]
35
+
36
+ if len(exst_run_nums) == 0:
37
+ curr_run = 1
38
+ else:
39
+ curr_run = max(exst_run_nums) + 1
40
+
41
+ # Create run directory
42
+ while True:
43
+ run_dir = model_dir / f'run{curr_run}'
44
+ # check every time we create one if another was created by a parallel process
45
+ try:
46
+ os.makedirs(run_dir)
47
+ except FileExistsError:
48
+ curr_run += 1
49
+ else:
50
+ break
51
+
52
+ return run_dir
53
+
54
+ def write_config(run_directory, cfg):
55
+ with open(os.path.join(run_directory, 'args.txt'), 'w') as f:
56
+ f.write(str(time.time()) + '\n')
57
+
58
+ # Write the git repo id
59
+ # commit_hash = Repo(
60
+ # search_parent_directories=True).head.object.hexsha
61
+ # f.write(
62
+ # "Running with git commit " + str(commit_hash) + '\n')
63
+
64
+ str_cfg = {key: str(val) for key, val in cfg.items()}
65
+
66
+ # Write the config
67
+ f.write("Configuration:\n")
68
+ f.write(json.dumps(str_cfg, indent=4))
69
+
70
+ # Write which files were modified since the last commit
71
+ # mod_files = get_modified_files()
72
+ # f.write("\nModified files since last commit:\n")
73
+ # f.write('\n'.join(str(i) for i in mod_files))
74
+
75
+ # Save code
76
+ # compress_python_files(os.path.join(run_directory, 'code.zip'))
77
+
78
+ #####################################################
79
+ # #
80
+ # Logger #
81
+ # #
82
+ #####################################################
83
+
84
+ class Logger:
85
+ """
86
+ Class to handle the logging of experiments locally.
87
+ """
88
+ def __init__(self, configuration, monitors):
89
+ assert 'xp_name' in configuration, "To log the experiment, define the experiment's name with the 'xp_name' entry."
90
+
91
+ self.configuration = configuration
92
+ self.monitors = monitors
93
+
94
+ self.log_directory = make_output_dirs(configuration)
95
+ print('Logging XP in directory:', self.log_directory)
96
+
97
+ write_config(self.log_directory, configuration)
98
+
99
+ def save_monitors(self):
100
+ data = []
101
+ for m in self.monitors.values():
102
+ m.make_plot_points(self.configuration["plot_window_size"])
103
+
104
+ data.append(pd.DataFrame(m.plot_points))
105
+
106
+ data = pd.concat(data, axis=1)
107
+
108
+ data.to_csv(self.log_directory / 'monitor_data.csv')
109
+
110
+
111
+
112
+
113
+
114
+
hermes/monitoring.py ADDED
@@ -0,0 +1,58 @@
1
+ ###########################################################
2
+ # #
3
+ # Monitoring #
4
+ # #
5
+ ###########################################################
6
+
7
+ import warnings
8
+ from itertools import islice
9
+ import numpy as np
10
+
11
+ from hermes.interaction import Interaction
12
+
13
+
14
+ class Monitor():
15
+ """General HERMES monitoring class"""
16
+
17
+ def __init__(self):
18
+ #Empty data traces upon initialisation:
19
+ self.data = []
20
+ self.plot_points = {}
21
+
22
+ self.line_name = "plot_points"
23
+
24
+ def flush(self):
25
+ self.data = []
26
+ self.plot_points = {}
27
+
28
+ def record(self):
29
+ """A monitor class defines a method for recording data."""
30
+ warnings.warn(f"Please implement a record_trace method for {type(self).__name__}")
31
+
32
+ def make_plot_points(self, window_size=100):
33
+ """Applies a sliding window to collected data that can be used for plotting."""
34
+ self.plot_points = {self.line_name: {}}
35
+ generator = fixed_step_window(self.data, window_size)
36
+ for w in generator:
37
+ self.plot_points[self.line_name][w[0]] = np.mean(w[1])
38
+
39
+
40
+ def fixed_step_window(seq, n=2):
41
+ for i in range(0, len(seq), n):
42
+ yield i+n, seq[i: i+n]
43
+
44
+
45
+ class TraceInteractionSuccess(Monitor):
46
+ """Monitor for tracing the success of interactions."""
47
+
48
+ def __init__(self, line_name="success"):
49
+ super().__init__()
50
+
51
+ self.line_name = line_name
52
+
53
+ def record(self, interaction: Interaction):
54
+ """Record 1 if interaction succeeded, 0 otherwise."""
55
+ if interaction.succeeded:
56
+ self.data.append(1)
57
+ else:
58
+ self.data.append(0)
hermes/population.py ADDED
@@ -0,0 +1,51 @@
1
+ ###########################
2
+ # #
3
+ # Populations #
4
+ # #
5
+ ###########################
6
+
7
+ import hermes.globals
8
+ import importlib
9
+ import sys
10
+ import random
11
+
12
+
13
+ class Population():
14
+ """The HERMES population class."""
15
+ def __init__(self, configuration):
16
+ self.configuration = {**hermes.globals.EXPERIMENT_DEFAULT_CONFIGURATION, **configuration}
17
+
18
+ def agent_list(self):
19
+ """Return all agents in the population in a list data structure."""
20
+ raise NotImplementedError("Please implement an 'agent_list' method for your 'Population' class.")
21
+
22
+ def save(self, path):
23
+ """Save the agents' learnt representations to the give path."""
24
+ raise NotImplementedError("Please implement a 'save' method for your 'Population' class.")
25
+
26
+ def load(self, path):
27
+ """Load saved representations."""
28
+ raise NotImplementedError("Please implement a 'load' method for your 'Population' class.")
29
+
30
+ class UniformPopulation(Population):
31
+ """A population where agents interact with other agents with a uniform probability."""
32
+
33
+ def __init__(self, configuration):
34
+ #Call initialisation method of super class:
35
+ super().__init__(configuration)
36
+
37
+ #Get agent class from configuration
38
+ class_name, module_name = self.configuration['agent_class']
39
+ module = importlib.import_module(module_name)
40
+ agent_class = getattr(module, class_name)
41
+
42
+ #Create list of agents of agent_class
43
+ self.agents = [agent_class(self.configuration) for i in range(configuration['population_size'])]
44
+
45
+ def sample_agents(self, nr_of_agents=2):
46
+ """Return two randomly sampled agents from the population."""
47
+
48
+ return random.sample(self.agents, nr_of_agents)
49
+
50
+ def agent_list(self):
51
+ return self.agents
hermes/process.py ADDED
@@ -0,0 +1,54 @@
1
+ ###########################################
2
+ # #
3
+ # Process. #
4
+ # #
5
+ ###########################################
6
+
7
+ class Process:
8
+ """The HERMES Process class."""
9
+
10
+ def __init__(self, agent, interaction):
11
+ self.agent = agent
12
+ self.interaction = interaction
13
+
14
+
15
+ class DescriptionProcess(Process):
16
+ """Given a context of entities, describe a given target entity."""
17
+
18
+ def __init__(self, agent, scene, target, interaction):
19
+ # Call initialisation method of super class
20
+ super().__init__(agent, interaction)
21
+
22
+ # Reset fields relevant to a description process upon its initialisation
23
+ self.scene = scene
24
+ self.target = target
25
+ self.utterance = None
26
+ self.applied_cxns = []
27
+ self.competitors = []
28
+
29
+
30
+ def run(self, phase):
31
+ """Run description process."""
32
+
33
+ self.utterance = self.agent.formulate(self.target, self.scene)
34
+ if self.utterance is None and phase != 'test':
35
+ self.utterance = self.agent.invent(self.target, self.scene)
36
+
37
+
38
+ class PointingProcess(Process):
39
+ """Given an utterance in a scene, point to the referent referred to by the utterance."""
40
+
41
+ def __init__(self, agent, scene, interaction):
42
+ # Call initialisation method of super class
43
+ super().__init__(agent, interaction)
44
+
45
+ self.scene = scene
46
+ self.observed_utterance = None
47
+ self.hypothesised_target = None
48
+
49
+ def run(self, utterance):
50
+ """Run pointing task: comprehend utterance and retrieve entity in the scene. Return target index."""
51
+
52
+ # Set process utterance to utterance and run comprehension
53
+ self.observed_utterance = utterance
54
+ self.hypothesised_target = self.agent.comprehend(utterance, self.scene)
hermes/utils.py ADDED
@@ -0,0 +1,19 @@
1
+ #####################################################
2
+ # #
3
+ # Utility funcitons for the hermes framework #
4
+ # #
5
+ #####################################################
6
+
7
+ import random
8
+
9
+ CONSONANTS = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z']
10
+ VOWELS = ['a', 'e', 'i', 'o', 'u', 'y']
11
+
12
+ def make_new_form(template=['C','V','C','V','C','V','C','V', 'C', 'V']):
13
+ word_characters = []
14
+ for type in template:
15
+ if type == 'C':
16
+ word_characters.append(random.choice(CONSONANTS))
17
+ else:
18
+ word_characters.append(random.choice(VOWELS))
19
+ return ''.join(word_characters)
hermes/world.py ADDED
@@ -0,0 +1,81 @@
1
+ #####################################################
2
+ # #
3
+ # World #
4
+ # #
5
+ #####################################################
6
+
7
+ import random
8
+ import numpy as np
9
+ import hermes.globals
10
+ import warnings
11
+
12
+ class World:
13
+ """The HERMES world class."""
14
+
15
+ def __init__(self, configuration):
16
+ self.configuration = {**hermes.globals.EXPERIMENT_DEFAULT_CONFIGURATION, **configuration}
17
+
18
+ def sample_scene_with_target(self):
19
+ warnings.warn("Please implement the 'sample_scene_with_target' method the 'World' class.")
20
+
21
+
22
+ class NamingGameWorld(World):
23
+ """A class for naming game worlds: each entity is an individual and there are no classes."""
24
+
25
+ def __init__(self, entities, configuration):
26
+ """Initialize the entity world."""
27
+
28
+ # Call the initialisation method of the super class, passing on the configuration
29
+ super().__init__(configuration)
30
+
31
+ # Set train_entities, val_entities and test_entities
32
+ self.entities = entities
33
+
34
+ def sample_scene_with_target(self, configuration):
35
+ "Sample scene with target."
36
+
37
+ scene_size = configuration['scene_size']
38
+ scene = random.sample(self.entities, scene_size)
39
+ target = random.choice(scene)
40
+
41
+ return scene, target
42
+
43
+ class EntityWorld(World):
44
+ """A class for worlds that consist of entities, where each entity belongs to a 'category' and a scene
45
+ typically does contain two entities of the same category."""
46
+
47
+ def __init__(self, train_entities_per_category, val_entities_per_category=None, test_entities_per_category=None, configuration={'scene_size': 5}):
48
+ """Create a grounded naming game world."""
49
+
50
+ super().__init__(configuration)
51
+
52
+ self.train_entities_per_category = train_entities_per_category
53
+ self.val_entities_per_category = val_entities_per_category
54
+ self.test_entities_per_category = test_entities_per_category
55
+
56
+
57
+ def sample_scene_with_target(self, configuration, split='train'):
58
+ "Sample scene with unique target."
59
+
60
+ # Choose right split
61
+ entities_per_category = None
62
+ if split == 'train':
63
+ entities_per_category = self.train_entities_per_category
64
+ elif split == 'val':
65
+ entities_per_category = self.val_entities_per_category
66
+ elif split == 'test':
67
+ entities_per_category = self.test_entities_per_category
68
+
69
+ # Sample unique categories to appear in scene
70
+ nr_of_categories_in_world = len(entities_per_category)
71
+ scene_size = configuration['scene_size']
72
+ scene_categories = random.sample(list(range(nr_of_categories_in_world)), scene_size)
73
+
74
+ # Create scene
75
+ scene = []
76
+ for category in scene_categories:
77
+ scene.append(random.choice(entities_per_category[category]))
78
+
79
+ # Then sample target from scene
80
+ target = random.choice(scene)
81
+ return scene, target
@@ -0,0 +1,108 @@
1
+ Metadata-Version: 2.4
2
+ Name: hermes-toolkit
3
+ Version: 0.1.0
4
+ Summary: A toolkit for the multi-agent simulation of emergent communication and languages.
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://gitlab.ai.vub.ac.be/ehai/hermes
7
+ Project-URL: Repository, https://gitlab.ai.vub.ac.be/ehai/hermes
8
+ Project-URL: Issues, https://gitlab.ai.vub.ac.be/ehai/hermes/-/issues
9
+ Keywords: emergent communication,language games,language evolution,multi-agent simulation,agent-based modelling
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: numpy
23
+ Requires-Dist: matplotlib
24
+ Requires-Dist: alive-progress
25
+ Provides-Extra: torch
26
+ Requires-Dist: torch; extra == "torch"
27
+ Provides-Extra: logging
28
+ Requires-Dist: pandas; extra == "logging"
29
+ Provides-Extra: all
30
+ Requires-Dist: torch; extra == "all"
31
+ Requires-Dist: pandas; extra == "all"
32
+ Provides-Extra: dev
33
+ Requires-Dist: pytest; extra == "dev"
34
+ Requires-Dist: build; extra == "dev"
35
+ Requires-Dist: twine; extra == "dev"
36
+ Dynamic: license-file
37
+
38
+ # HERMES
39
+
40
+ *A toolkit for the multi-agent simulation of emergent communication and languages.*
41
+
42
+ HERMES provides the building blocks for running language games: populations of
43
+ agents, worlds that supply the entities agents talk about, interaction scripts
44
+ that define who says what to whom, alignment strategies that update agents after
45
+ each interaction, and monitors that record how the emerging language develops
46
+ over time.
47
+
48
+ ## Installation
49
+
50
+ ```bash
51
+ pip install hermes-toolkit
52
+ ```
53
+
54
+ The core framework is pure Python. Experiments with neurally grounded agents
55
+ additionally need PyTorch, and the experiment logger needs pandas:
56
+
57
+ ```bash
58
+ pip install "hermes-toolkit[all]" # torch + pandas
59
+ pip install "hermes-toolkit[torch]" # torch only
60
+ ```
61
+
62
+ The distribution is named `hermes-toolkit`, but the package is imported as
63
+ `hermes`:
64
+
65
+ ```python
66
+ import hermes
67
+ from hermes.experiment import Experiment
68
+ ```
69
+
70
+ ## Getting started
71
+
72
+ Worked examples live in [`docs/source/tutorials`](docs/source/tutorials):
73
+
74
+ - `hermes_naming_game.ipynb` — a basic naming game
75
+ - `hermes_grounded_naming_game.ipynb` — a naming game grounded in images
76
+ - `hermes-MARL-concept-learning.ipynb` — concept learning with neural agents
77
+ - `hermes_naming_game_pyfcg.ipynb` — integration with FCG
78
+
79
+ ## Core concepts
80
+
81
+ | Component | Role |
82
+ |---|---|
83
+ | `Agent` | Holds a vocabulary and whatever machinery it needs to produce and interpret utterances |
84
+ | `Population` | Determines which agents interact with one another |
85
+ | `World` | Supplies the scenes and entities agents communicate about |
86
+ | `Interaction` | The script of a single communicative exchange |
87
+ | `Process` | One participant's contribution to an interaction (describing, pointing, drawing, ...) |
88
+ | `AlignmentStrategy` | How agents update after success or failure |
89
+ | `Monitor` | Records a measure over the course of an experiment |
90
+ | `Experiment` | Ties the above together and runs series of interactions |
91
+
92
+ Experiments are configured with a dictionary; each component is given as a
93
+ `(class_name, module_name)` pair, so your own subclasses drop in without
94
+ changing the framework.
95
+
96
+ ## Citation
97
+
98
+ If you use HERMES in academic work, please cite it. A `CITATION.cff` file will
99
+ be added with the first tagged release.
100
+
101
+ ## Contributing
102
+
103
+ The `main` branch is protected — please create a feature branch for your
104
+ contribution and open a merge request against `main`.
105
+
106
+ ## License
107
+
108
+ Apache License 2.0 — see [LICENSE](LICENSE).
@@ -0,0 +1,17 @@
1
+ hermes/__init__.py,sha256=52GvXk3jf7Wi20T2qEO30ji8lUqsoX16wPj1FlaEJTo,347
2
+ hermes/agent.py,sha256=FfvcR5JZSOZkTBPLBrNUUVj8DBEi9NTZMZR00IGAygA,1379
3
+ hermes/alignment.py,sha256=OCv1l5qvp1msnJMqa7hcsciqAdaSkwiDACnxWOpnwnQ,293
4
+ hermes/experiment.py,sha256=H31Cx_NNINsbnPips_m1odzfuhBz4UH7hYI0ecx6ABE,6394
5
+ hermes/globals.py,sha256=8ZGAbqLS5kvYrit3N8mzvhROrnfaFix25t4HTh6Gco4,1801
6
+ hermes/interaction.py,sha256=aRn6_HyLyNmj7qa_K21K0R5GLgj4FHkVRGxyP6GPsXY,5398
7
+ hermes/logging.py,sha256=Xc5oKheVEWked-c5meIsChDRGSKsIjC4ipxjHJk0N1k,3489
8
+ hermes/monitoring.py,sha256=UBbdsaDDIhfuamndwjmSR7-CAmVkqIPvoo2aLI303vQ,1769
9
+ hermes/population.py,sha256=jQ2yq-8s6FFeeaHyezROfGq8KGIuGiP2daDxZG-X9WU,1835
10
+ hermes/process.py,sha256=tifMHK-vrxwfeK9YtTfRmRDvUtk_SqJD0KtUeEDjA6c,1857
11
+ hermes/utils.py,sha256=9eD88PZEY-tt1m3D3PC_i_S0Ok8OnHgJ7SZ2HTTdg0w,759
12
+ hermes/world.py,sha256=rZgyQaTBudYsVr1u7UVfo8WSFMpkxnNuAxLanxY7QTM,3060
13
+ hermes_toolkit-0.1.0.dist-info/licenses/LICENSE,sha256=zL8bSaRwYIf1q6vtu_bAHVA0BmOPekGZIui_VF4ZMoE,11344
14
+ hermes_toolkit-0.1.0.dist-info/METADATA,sha256=N2cmpNgalOvTPH3iPt_Fd9w1dwX2VDGOFmHzhw79HnU,3943
15
+ hermes_toolkit-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
16
+ hermes_toolkit-0.1.0.dist-info/top_level.txt,sha256=1TupzjD_10P0-QWmHdzyxP4OXHKizFdjhlf91BcdH28,7
17
+ hermes_toolkit-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 Paul Van Eecke
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ hermes