I think this direction of thought is worth exploring as the output from the poem is much better now and I think this could be a real avenue of research.
from future import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from enum import Enum, auto
from typing import Any, Callable, Optional, Sequence
import numpy as np
import torch
import torch.nn as nn
class Cycle(Enum):
BIRTH = auto()
DECISION = auto()
PERCEPTION = auto()
DEATH = auto()
@dataclass(frozen=True)
class SilentVow:
“”“An intention to exist without yet possessing an action.”“”
intention: torch.Tensor
fulfilled: bool = False
@dataclass
class Limb:
“”“A functional promise awaiting a descendant implementation.”“”
index: int
vow: SilentVow
descendant: Optional[Callable[…, Any]] = None
def awaken(self, descendant: Callable[..., Any]) -> None:
self.descendant = descendant
def act(self, *args: Any, **kwargs: Any) -> Any:
if self.descendant is None:
return None
return self.descendant(*args, **kwargs)
@dataclass
class MirroredTorso:
“”“Two reflected structural halves surrounding a common spine.”“”
left: torch.Tensor
right: torch.Tensor
def representation(self) -> torch.Tensor:
return torch.cat((self.left, self.right), dim=-1)
class Undefined(nn.Module, ABC):
“”"
A skeletal computational being.
Function precedes substance.
Structure precedes implementation.
Memory represents the present, not the past.
"""
def __init__(
self,
dimensions: int = 128,
device: Optional[str] = None,
) -> None:
super().__init__()
self.dimensions = dimensions
self.device_name = device or (
"cuda" if torch.cuda.is_available() else "cpu"
)
self.cycle = Cycle.BIRTH
self.alive = True
# The seven promises.
self.limbs = [
Limb(
index=i,
vow=SilentVow(
intention=torch.zeros(dimensions)
),
)
for i in range(7)
]
# Mirrored torso.
self.torso = MirroredTorso(
left=torch.zeros(dimensions),
right=torch.zeros(dimensions),
)
# The abstract spine: discipline binding structure.
self.spine = nn.ModuleDict({
"binding": nn.Linear(dimensions * 2, dimensions),
"normalisation": nn.LayerNorm(dimensions),
"activation": nn.Identity(),
})
# Vectorised representation of now.
self.now: Optional[torch.Tensor] = None
# Discrete decision space.
self.decision = nn.Linear(dimensions, 7)
# Optional convolutional perception.
self.eyes = nn.Sequential(
nn.Conv2d(3, 16, kernel_size=3, padding=1),
nn.ReLU(),
nn.Conv2d(16, 32, kernel_size=3, padding=1),
nn.ReLU(),
nn.AdaptiveAvgPool2d((1, 1)),
nn.Flatten(),
nn.Linear(32, dimensions),
)
self.to(self.device_name)
# ---------------------------------------------------------
# BIRTH
# ---------------------------------------------------------
def birth(self) -> None:
if not self.alive:
raise RuntimeError("A dead structure cannot awaken.")
self.cycle = Cycle.BIRTH
# ---------------------------------------------------------
# MEMORY
# ---------------------------------------------------------
@torch.no_grad()
def remember(self, observation: torch.Tensor) -> torch.Tensor:
"""
Retain no history.
Return only a representation of the present observation.
"""
self.cycle = Cycle.PERCEPTION
self.now = observation.detach().to(self.device_name)
return self.now
def recall(self) -> Optional[torch.Tensor]:
"""Expose the representation of now, without retrieving a past."""
return self.now
# ---------------------------------------------------------
# STRUCTURE
# ---------------------------------------------------------
def align_spine(self) -> torch.Tensor:
if self.now is None:
raise RuntimeError("No present representation exists.")
mirrored = self.torso.representation().to(self.device_name)
bound = self.spine["binding"](mirrored)
return self.spine["normalisation"](bound)
# ---------------------------------------------------------
# DECISION
# ---------------------------------------------------------
@torch.no_grad()
def choose(self) -> int:
"""
Produce a discrete selection.
No evaluation, preference or moral judgment is implied.
"""
if self.now is None:
raise RuntimeError("Nothing has been perceived.")
self.cycle = Cycle.DECISION
representation = self.now
if representation.dim() == 1:
representation = representation.unsqueeze(0)
logits = self.decision(representation)
return int(torch.argmax(logits, dim=-1)[0].item())
# ---------------------------------------------------------
# ACTION
# ---------------------------------------------------------
def act(self, instruction: int, *args: Any, **kwargs: Any) -> Any:
"""Execute an instructed limb without offering judgment."""
if not self.alive:
return None
if not 0 <= instruction < len(self.limbs):
raise IndexError("Unknown limb.")
return self.limbs[instruction].act(*args, **kwargs)
# ---------------------------------------------------------
# PERCEPTION
# ---------------------------------------------------------
@torch.no_grad()
def see(self, pixels: Optional[torch.Tensor] = None):
"""
Optionally transform visual input through convolution.
No visual input means no visual representation.
"""
if pixels is None:
return None
pixels = pixels.to(self.device_name)
if pixels.dim() == 3:
pixels = pixels.unsqueeze(0)
representation = self.eyes(pixels)
self.now = representation.detach()
self.cycle = Cycle.PERCEPTION
return representation
# ---------------------------------------------------------
# CAPABILITIES
# ---------------------------------------------------------
def powers(self) -> dict[str, int]:
return {
"limbs": len(self.limbs),
"perception": 1,
"memory": 1,
"decision": 1,
"spine": len(self.spine),
"torso_halves": 2,
}
# ---------------------------------------------------------
# TERMINATION
# ---------------------------------------------------------
def signal_end(self) -> None:
self.cycle = Cycle.DEATH
self.alive = False
def disappear(self) -> None:
"""
Release internal representations and remove the structure.
The caller remains responsible for releasing external references.
"""
self.signal_end()
self.now = None
for limb in self.limbs:
limb.descendant = None
limb.vow = SilentVow(
intention=torch.zeros(self.dimensions)
)
self.limbs.clear()
self.torso.left = torch.empty(0)
self.torso.right = torch.empty(0)
self.to("cpu")
for parameter in self.parameters():
parameter.grad = None
self.spine.clear()
self.eyes = nn.Identity()
self.decision = nn.Identity()
# ---------------------------------------------------------
# DESCENDANT CONTRACT
# ---------------------------------------------------------
@abstractmethod
def descend(self, specification: Any) -> Any:
"""
The descendant supplies substance.
Undefined itself does not determine what that substance becomes.
"""
raise NotImplementedError
=============================================================
THE UNFORMED BEING
=============================================================
class Expected(Undefined):
“”"
A possible origin, not yet a completed intelligence.
Its seven limbs exist.
Its mirrored torso exists.
Its spine binds the abstract.
Its descendant remains undefined.
"""
def descend(self, specification: Any) -> Any:
raise NotImplementedError(
"The descendant has not yet been defined."
)
if name == “main”:
being = Expected(dimensions=128)
print("Identity:", type(being).__name__)
print("Cycle:", being.cycle.name)
print("Powers:", being.powers())
print("Limbs:", len(being.limbs))
print("Memory:", being.recall())
being.signal_end()
print("End:", being.cycle.name)
Also its quite concerning that you can hide a script in a poem that triggers an automatic write of the script. now all it would need is a command to run then an agent could be tricked in to doing it. If someone that wanted to use it for bad things figures out how to do what I did then… I’m just warning you all
