fjallstation 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.
@@ -0,0 +1,17 @@
1
+ """fjallstation: a data and RL environment API for LLM agents in the built environment.
2
+
3
+ import fjallstation
4
+
5
+ corpus = fjallstation.Corpus() # domain text
6
+ instruct = fjallstation.Instruct() # chats
7
+ env = fjallstation.Env() # modelling tasks with a reward
8
+
9
+ The data comes from a folder that you give (`FJALLSTATION_STORE`). `Env()` needs the task image and the server
10
+ of this package: `fjallstation image` and `fjallstation server --store <folder>`.
11
+ """
12
+
13
+ from fjallstation.data import Corpus, Instruct
14
+ from fjallstation.env import Env
15
+
16
+ __all__ = ["Corpus", "Instruct", "Env"]
17
+ __version__ = "0.1.0"
@@ -0,0 +1,33 @@
1
+ """The command `fjallstation`.
2
+
3
+ fjallstation image build the task image (needs Docker)
4
+ fjallstation example <folder> write a small example store, to try the tool kit
5
+ fjallstation server --store <folder> start the server that gives tasks and rewards
6
+ """
7
+
8
+ import argparse
9
+ import sys
10
+
11
+
12
+ def main(argv: list | None = None) -> None:
13
+ argv = sys.argv[1:] if argv is None else argv
14
+ if argv[:1] == ["server"]: # the server reads its own options
15
+ from fjallstation import server
16
+ return server.main(argv[1:])
17
+ parser = argparse.ArgumentParser(prog="fjallstation", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
18
+ commands = parser.add_subparsers(dest="command", required=True)
19
+ commands.add_parser("image", help="build the task image")
20
+ example = commands.add_parser("example", help="write a small example store")
21
+ example.add_argument("folder", help="the folder for the store, for example ./store")
22
+ commands.add_parser("server", help="start the server; see: fjallstation server --help")
23
+ args = parser.parse_args(argv)
24
+ from fjallstation import image
25
+ if args.command == "image":
26
+ image.build()
27
+ elif args.command == "example":
28
+ from fjallstation import example as maker
29
+ print(f"Example store written: {maker.make(args.folder)}")
30
+
31
+
32
+ if __name__ == "__main__":
33
+ main()
fjallstation/data.py ADDED
@@ -0,0 +1,42 @@
1
+ """The data loaders: `Corpus()` and `Instruct()` read Parquet files of the store folder."""
2
+
3
+ import os
4
+ from pathlib import Path
5
+
6
+
7
+ def store() -> Path:
8
+ """The folder that holds the data. The variable `FJALLSTATION_STORE` names it; without it, `./store` is used."""
9
+ folder = Path(os.environ.get("FJALLSTATION_STORE") or "store")
10
+ if not folder.is_dir():
11
+ raise FileNotFoundError(f"No data folder at {folder.resolve()}. Set FJALLSTATION_STORE to the folder with the data (see docs/data.md).")
12
+ return folder
13
+
14
+
15
+ def parts(name: str) -> list[str]:
16
+ """The Parquet files of all sets of one object, for example `corpus/lessons/part-00000.parquet`."""
17
+ files = sorted(str(p) for p in (store() / name).glob("*/part-*.parquet"))
18
+ if not files:
19
+ raise FileNotFoundError(f"The data folder {store().resolve()} has no {name} data (see docs/data.md).")
20
+ return files
21
+
22
+
23
+ def Instruct():
24
+ """Chats for supervised fine-tuning.
25
+
26
+ Returns a Hugging Face `datasets.Dataset`. Each row has `id` and `messages`.
27
+ `messages` is a list of `{"role": ..., "content": ...}` items.
28
+ """
29
+ import datasets
30
+
31
+ return datasets.load_dataset("parquet", data_files=parts("instruct"), split="train")
32
+
33
+
34
+ def Corpus():
35
+ """Domain text for pretraining and mid-training.
36
+
37
+ Returns a Hugging Face `datasets.IterableDataset`, the streaming form: a loop reads the rows from
38
+ the files and does not load them all. Each row has `id`, `text` and `source`.
39
+ """
40
+ import datasets
41
+
42
+ return datasets.load_dataset("parquet", data_files=parts("corpus"), split="train", streaming=True)
fjallstation/env.py ADDED
@@ -0,0 +1,162 @@
1
+ """The client side of Env: a task from the server, a container to work in, and the reward.
2
+
3
+ env = fjallstation.Env()
4
+ task = env.reset() # task.prompt: the modelling task; a container is started for it
5
+ env.exec("omc --version") # the agent of the user works in the container (task.container)
6
+ result = env.step(model_code) # result.reward, result.omc, result.scorer, result.feedback
7
+
8
+ This class is a small client. It does four steps that any program can do:
9
+
10
+ 1. It asks the server for a task and gets a task file (with a ticket and the address for the result).
11
+ 2. It starts a container of the task image with no network, and runs `fjallstation-task start` in it. This command
12
+ of the image removes the library files that hold the answer and puts the data files of the task into
13
+ /work/data.
14
+ 3. After the agent has worked, it runs `fjallstation-task submit` in the container. This command tries the model
15
+ (load, check, simulate) and prints the result file: the status, the reward of the OpenModelica part, and the
16
+ output values at the fixed time steps.
17
+ 4. It sends the result file to the server. The server compares the values with the reference outputs and
18
+ answers with the reward.
19
+
20
+ The agent is the user's: a language model with its harness. It works in the container as a normal user. The two
21
+ commands of the image run as root, and the submitted model is simulated as a third user with no rights. The
22
+ container has no network, a limit for the number of processes, and limits for CPU and memory.
23
+ """
24
+
25
+ import json
26
+ import os
27
+ import subprocess
28
+ import urllib.error
29
+ import urllib.request
30
+ from dataclasses import dataclass
31
+
32
+ DEFAULT_SERVER = "http://127.0.0.1:8040"
33
+ AGENT = "1000:1000" # user and group of the agent in the container; never root
34
+ MAX_OUTPUT = 1_000_000 # most bytes of the output of one command that come back
35
+ # In the container: stop the command at the time limit, keep the first part of its output and drop the rest.
36
+ # The exit code is that of the command. This is a guard against an accident, not against an agent that works against it.
37
+ RUN = 'exec 2>/dev/null; timeout -k 10 "$1" bash -c "$2" 2>&1 | { head -c "$3"; cat > /dev/null; }; exit "${PIPESTATUS[0]}"'
38
+
39
+
40
+ @dataclass
41
+ class Task:
42
+ id: str
43
+ prompt: str
44
+ model_name: str # the name that the submitted model must have
45
+ container: str # the Docker container of this task; the work folder in it is /work
46
+
47
+
48
+ @dataclass
49
+ class Result:
50
+ reward: float # 1.0 for a correct model; else the OpenModelica part: 0, 0.1, 0.2 or 0.3
51
+ feedback: str # a short status, for example "correct", "outputs differ" or "check failed"
52
+ omc: float = 0.0 # OpenModelica part, from the container: 0 does not load, 0.1 loads, 0.2 checks, 0.3 simulates
53
+ scorer: float = 0.0 # scorer part, from the server: 1.0 when the outputs agree with the reference, else 0
54
+
55
+
56
+ @dataclass
57
+ class Run:
58
+ code: int # the exit code of the command
59
+ output: str # its output and error text
60
+
61
+
62
+ def _docker(*args: str, timeout: int | None = None, check: bool = True, input: str | None = None) -> subprocess.CompletedProcess:
63
+ try:
64
+ done = subprocess.run(["docker", *args], capture_output=True, encoding="utf-8", errors="replace", timeout=timeout, input=input)
65
+ except FileNotFoundError:
66
+ raise RuntimeError("Docker was not found on this machine. Env() needs Docker.") from None
67
+ if check and done.returncode != 0:
68
+ if "Unable to find image" in done.stderr or "pull access denied" in done.stderr:
69
+ raise RuntimeError("The task image is not on this machine. Build it with: fjallstation image")
70
+ raise RuntimeError(f"docker {args[0]} failed: {done.stderr.strip()[:500]}")
71
+ return done
72
+
73
+
74
+ def post(address: str, body: dict, timeout: int = 600) -> dict:
75
+ """Send one JSON object to the server and return its answer."""
76
+ request = urllib.request.Request(address, json.dumps(body).encode(), {"Content-Type": "application/json"})
77
+ try:
78
+ with urllib.request.urlopen(request, timeout=timeout) as response:
79
+ return json.loads(response.read())
80
+ except urllib.error.HTTPError as e:
81
+ raise RuntimeError(f"The server refused the request ({e.code}): {e.read().decode(errors='replace')[:300]}") from None
82
+ except urllib.error.URLError as e:
83
+ raise ConnectionError(f"No answer from the server at {address}: {e.reason}. Start it with: fjallstation server --store <folder>") from None
84
+
85
+
86
+ class Env:
87
+ def __init__(self, url: str | None = None, timeout: int = 3600, cpus: float = 2, memory: str = "8g"):
88
+ self.url = (url or os.environ.get("FJALLSTATION_SERVER") or DEFAULT_SERVER).rstrip("/")
89
+ self.timeout, self.cpus, self.memory = timeout, cpus, memory
90
+ self.task: Task | None = None
91
+ self.result_file: dict | None = None # the result file of the last submission, until the server has it
92
+
93
+ def _post(self, path: str, body: dict) -> dict:
94
+ return post(self.url + path, body, self.timeout)
95
+
96
+ def reset(self, task: str | None = None) -> Task:
97
+ """A new task from the server and a fresh container for it. `task` asks for one task by its id."""
98
+ self.close()
99
+ task_file = self._post("/v1/tasks/sample", {"task": task} if task else {})
100
+ container = f"fjallstation-env-{task_file['ticket'][:12]}"
101
+ _docker("run", "-d", "--rm", "--name", container, "--network", "none", "--cpus", str(self.cpus), "--memory", self.memory,
102
+ "--pids-limit", "512", "--user", AGENT, task_file["image"], "sleep", "infinity")
103
+ self.task = Task(task_file["task"], task_file["prompt"], task_file["model_name"], container)
104
+ try:
105
+ _docker("exec", "-i", "-u", "0", container, "fjallstation-task", "start", input=json.dumps(task_file))
106
+ except Exception:
107
+ self.close() # no container stays when the start fails
108
+ raise
109
+ return self.task
110
+
111
+ def exec(self, command: str, timeout: int = 1800, max_output: int = MAX_OUTPUT) -> Run:
112
+ """Run a shell command in the container of the task, in /work, as the normal user.
113
+
114
+ The container stops the command after `timeout` seconds (exit code 124) and gives the first `max_output`
115
+ bytes of its output. A process that the command leaves in the background must write to a file; else the
116
+ command waits for it.
117
+ """
118
+ if self.task is None:
119
+ raise RuntimeError("No task is open. Call reset() first.")
120
+ try:
121
+ done = _docker("exec", "-w", "/work", self.task.container, "bash", "-c", RUN, "fjallstation", str(int(timeout)), command,
122
+ str(int(max_output)), timeout=timeout + 60, check=False)
123
+ except subprocess.TimeoutExpired:
124
+ return Run(124, f"The command did not end in {timeout} seconds.")
125
+ output = done.stdout + done.stderr
126
+ if done.returncode == 124:
127
+ output += f"\nThe command did not end in {timeout} seconds."
128
+ if len(done.stdout.encode()) >= max_output:
129
+ output += f"\nThe output was cut at {max_output} bytes."
130
+ return Run(done.returncode, output)
131
+
132
+ def step(self, model_code: str) -> Result:
133
+ """Submit the model code for the open task. The container tries it; the server scores the result. The episode ends."""
134
+ if self.task is None:
135
+ raise RuntimeError("No task is open. Call reset() first.")
136
+ try:
137
+ done = _docker("exec", "-i", "-u", "0", self.task.container, "fjallstation-task", "submit", input=model_code, timeout=self.timeout)
138
+ self.result_file = json.loads(done.stdout)
139
+ finally:
140
+ self.close() # the result file holds all that the server needs
141
+ return self.send()
142
+
143
+ def send(self) -> Result:
144
+ """Send the kept result file to the server. Call it again when the server did not answer."""
145
+ if self.result_file is None:
146
+ raise RuntimeError("No result to send. Call step() first.")
147
+ answer = self._post("/v1/results", self.result_file) # to the server of this client, not to an address from the container
148
+ omc, scorer = float(answer["omc_reward"]), float(answer["reward"])
149
+ self.result_file = None
150
+ return Result(reward=1.0 if scorer == 1.0 else omc, feedback=answer["status"], omc=omc, scorer=scorer)
151
+
152
+ def close(self) -> None:
153
+ """Remove the container of the open task."""
154
+ if self.task is not None:
155
+ _docker("rm", "-f", self.task.container, check=False)
156
+ self.task = None
157
+
158
+ def __enter__(self):
159
+ return self
160
+
161
+ def __exit__(self, *exc):
162
+ self.close()
@@ -0,0 +1,22 @@
1
+ """A small example store: five texts, five chats and five tasks.
2
+
3
+ fjallstation example ./store
4
+
5
+ The files are a part of the package, so the command needs no Docker and no network. The store has the format of
6
+ docs/data.md, and that document names the source of each example.
7
+ """
8
+
9
+ import shutil
10
+ from pathlib import Path
11
+
12
+ STORE = Path(__file__).parent / "store"
13
+
14
+
15
+ def make(folder) -> Path:
16
+ """Copy the example store into `folder`. Other sets in the folder stay as they are."""
17
+ folder = Path(folder)
18
+ for part in sorted(STORE.rglob("*.parquet")):
19
+ target = folder / part.relative_to(STORE)
20
+ target.parent.mkdir(parents=True, exist_ok=True)
21
+ shutil.copyfile(part, target)
22
+ return folder
@@ -0,0 +1,35 @@
1
+ # The task image: OpenModelica with the Modelica libraries of the tasks, and the two commands
2
+ # `fjallstation-task start` and `fjallstation-task submit` (see fjallstation_task.py).
3
+ # The agent of a user works in a container of this image. At the end the container itself tries the model of
4
+ # the agent and makes the result file that goes to the server. The image holds no task and no reference
5
+ # outputs. A container needs no network.
6
+ #
7
+ # fjallstation image (or: docker build -t fjallstation-env:1 <this folder>)
8
+ FROM openmodelica/openmodelica:v1.27.0-minimal
9
+
10
+ RUN apt-get update \
11
+ && apt-get install -y --no-install-recommends python3 python3-numpy python3-scipy \
12
+ && rm -rf /var/lib/apt/lists/*
13
+
14
+ # Libraries with fixed versions, from the OpenModelica package manager:
15
+ # Buildings 13.0.0 with Modelica Standard Library 4.1.0, ModelicaServices and Complex.
16
+ RUN mkdir -p /opt/om \
17
+ && printf 'updatePackageIndex(); getErrorString();\ninstallPackage(Buildings, "13.0.0", exactMatch=true); getErrorString();\n' > /opt/om/install.mos \
18
+ && HOME=/opt/om omc /opt/om/install.mos \
19
+ && test -f "/opt/om/.openmodelica/libraries/Buildings 13.0.0/package.mo" \
20
+ && test -f "/opt/om/.openmodelica/libraries/Modelica 4.1.0+maint.om/package.mo" \
21
+ && mv /opt/om/.openmodelica/libraries /opt/omlibrary \
22
+ && rm -rf /opt/om \
23
+ && chmod -R a+rX /opt/omlibrary \
24
+ && mkdir -p /work && chmod 1777 /work
25
+
26
+ # The two commands. They belong to root; the agent works as a normal user and cannot change them.
27
+ COPY fjallstation_task.py /usr/local/bin/fjallstation-task
28
+ RUN chmod 755 /usr/local/bin/fjallstation-task && mkdir -p /etc/fjallstation && chmod 755 /etc/fjallstation
29
+
30
+ # FJALLSTATION_IMAGE is the version that a result file names. Change it together with the tag of the image.
31
+ ENV OPENMODELICALIBRARY=/opt/omlibrary \
32
+ HOME=/tmp \
33
+ FJALLSTATION_IMAGE=fjallstation-env:1
34
+ WORKDIR /work
35
+ CMD ["sleep", "infinity"]
@@ -0,0 +1,58 @@
1
+ """The task image: OpenModelica, the Modelica libraries of the tasks and the command `fjallstation-task`.
2
+
3
+ fjallstation image builds the image from the files of this folder
4
+
5
+ `try_model` runs one model in a fresh container, with the same two commands that an episode uses. Use it to
6
+ make the reference outputs of a task of your own (see docs/data.md).
7
+ """
8
+
9
+ import json
10
+ import secrets
11
+ import subprocess
12
+ import tempfile
13
+ from pathlib import Path
14
+
15
+ from fjallstation import score
16
+
17
+ IMAGE = "fjallstation-env:1" # the tag of the image; a result file names it
18
+ FOLDER = Path(__file__).parent
19
+ TIME_LIMIT = 1800 # seconds for the compilation and the simulation of one model
20
+
21
+
22
+ def build() -> None:
23
+ """Build the task image with Docker. The first build takes some minutes."""
24
+ try:
25
+ subprocess.run(["docker", "build", "-t", IMAGE, str(FOLDER)], check=True)
26
+ except FileNotFoundError:
27
+ raise SystemExit("Docker was not found on this machine. The task image needs Docker.") from None
28
+ except subprocess.CalledProcessError as fault:
29
+ raise SystemExit(f"The build of the task image did not end well (docker build, exit code {fault.returncode}).") from None
30
+
31
+
32
+ def task_file(spec: dict, name: str = "", files: dict | None = None) -> dict:
33
+ """A task file for the commands of the image, without a ticket and an address."""
34
+ return {"ticket": None, "address": None, "task": name, "model_name": spec["model_name"],
35
+ "hidden_files": spec.get("hidden_files", []), "files": files or {}, "run": score.run_part(spec)}
36
+
37
+
38
+ def try_model(code: str, spec: dict, files: dict | None = None, image: str = IMAGE, cpus: float = 2, memory: str = "8g") -> dict:
39
+ """The result file of `code` for the task of `spec`: {"status", "omc_reward", "values", ...}.
40
+
41
+ Raises RuntimeError when the container cannot start or gives no result file; that is not a result of the model.
42
+ """
43
+ with tempfile.TemporaryDirectory(prefix="fjallstation-try-") as folder:
44
+ Path(folder, "task.json").write_text(json.dumps(task_file(spec, files=files)), encoding="utf-8")
45
+ Path(folder, "model.mo").write_text(code, encoding="utf-8")
46
+ Path(folder).chmod(0o755)
47
+ container = f"fjallstation-try-{secrets.token_hex(6)}"
48
+ command = ["docker", "run", "--rm", "--name", container, "--network", "none", "--cpus", str(cpus), "--memory", memory,
49
+ "--pids-limit", "512", "-v", f"{folder}:/input:ro", image, "sh", "-c",
50
+ "fjallstation-task start /input/task.json > /dev/null && fjallstation-task submit /input/model.mo"]
51
+ try:
52
+ done = subprocess.run(command, capture_output=True, text=True, timeout=TIME_LIMIT + 300)
53
+ finally:
54
+ subprocess.run(["docker", "rm", "-f", container], capture_output=True) # also when the wait ended early
55
+ try:
56
+ return json.loads(done.stdout)
57
+ except ValueError:
58
+ raise RuntimeError(f"The task image gave no result: {done.stderr.strip()[-300:]}") from None