Skip to content

8 · A teaching world

The previous chapters introduced each piece of the classroom on its own. This chapter follows one complete round of the fourth stage (tutorial_steps/step4): three lectures and an exam. It shows how the actions of the teacher, the requested actions of the students and the timing of the streams fit together. The fifth stage adds the forms for people and the sixth the statistics. The teaching loop itself does not change after the fourth stage. Its timing does change and the snippets of this chapter quote the final world in src/. In that version the constants allow each step 2.5 times the delta of its stream.

The timing of the class

All the durations of the classroom derive from a few constants of the teacher:

src/teacher.py
LECTURE_SAMPLES = 6                                   # pictures per lecture
LECTURE_DELTA = 7.0                                   # seconds between two pictures
LECTURE_RESPONSE_DELTA = 2.5 * LECTURE_DELTA          # 17.5 s: time allowed for one step
LECTURE_MAX_DURATION = LECTURE_RESPONSE_DELTA * LECTURE_SAMPLES

EXAM_SAMPLES = 6
EXAM_OR_FEEDBACK_DELTA = 10.0
EXAM_OR_FEEDBACK_RESPONSE_DELTA = 2.5 * EXAM_OR_FEEDBACK_DELTA   # 25 s
EXAM_MAX_DURATION = EXAM_OR_FEEDBACK_RESPONSE_DELTA * EXAM_SAMPLES

The deltas pace the streams of the teacher and the maximum durations bound the lifetime of each interaction. The behavior of the student uses the response deltas as the timeouts of learn and process. Because world.py imports the teacher class to build the student behavior, one file holds all the timing of both roles.

Lectures

A lecture takes three transitions of the teacher:

  1. in_class → ready_for_lecture runs give_next_lecture. The action fails after the third lecture. Otherwise it announces the lecture to every student with a volatile print (chapter 5).
  2. ready_for_lecture → lecture_in_progress runs teach after the 8 seconds of waiting time of ready_for_lecture. teach sends the interaction learn to every student with the two streams of the lecture (chapter 6). The fixed identifier of the interaction (lecture1_uuid, lecture2_uuid or lecture3_uuid) ties the samples of the two streams to that interaction.
  3. lecture_in_progress → in_class runs lecture_finished. The action returns False until the callback mark_lecture_as_finished has marked the lecture as finished and the last answers have had time to arrive (chapter 5).

The request reaches each student in the state in_class. The built-in learn action runs one step for each pair of picture and class name. In each step the processor predicts from the picture, the loss compares the prediction with the class index derived from the class name and the optimizer updates the model. The student declares the optimizer and the loss in proc_opts when it creates its agent:

run_student1.py (abridged)
agent = Agent(proc=net,
              proc_inputs=[StreamType(data_type="img",
                                      stream_to_proc_transforms=transforms_factory("rgb224"))],
              proc_outputs=[StreamType(data_type="text",
                                       stream_to_proc_transforms=net.get_class_ids,
                                       proc_to_stream_transforms=net.get_class_names)],
              proc_opts={'optimizer': torch.optim.SGD(net.parameters(), lr=0.5),
                         'losses': [torch.nn.functional.cross_entropy]})

get_class_ids turns class names into indices and gives a new index to a class it has never seen. Lecture after lecture the network learns two new classes without seeing the old ones again. Its head of Continual Neural Units (LinearCNU from unaiverse.modules.cnu.layers) is a layer designed for continual learning. In this setting the model must not forget the old classes while new ones arrive.

When six steps are done, the student takes in_class → done_learning and then nop back to in_class. If a step does not arrive within 17.5 seconds, the timeout of the transition expires and the student gives up the lecture. The interaction then completes with a non-OK reason on the side of the teacher.

The exam

After the third lecture give_next_lecture fails and the machine leaves in_class through start_exam_session. The exam takes three steps:

  1. start_exam_session clears the samples of the previous exam and announces the exam.
  2. hand_out_exam sends process to every student with the exam pictures on stdin and their class names on stdext. self.get_last_sent_interaction().target lists the students who actually received the exam and the action keeps that list as current_students.
  3. The loop exam_in_progress → exam_in_progress runs on_data(stream_group="exam") while samples go out and answers come back. exam_in_progress → in_class runs evaluate_results. This action waits for the callback mark_exam_as_finished.
sequenceDiagram
    autonumber
    participant T as Teacher
    participant S as Student
    T->>S: interaction "process" (stdin: images@exam, stdext: class_names@exam, 6 steps)
    loop 6 pictures, one every 10 s
        T-->>S: picture (and class name, kept aside)
        T->>T: on_data: record the picture and its true class
        S->>S: process: predict
        S-->>T: predicted class name on the processor stream
        T->>T: on_data: record the answer of S for that picture
    end
    S-->>T: status: completed
    T->>T: mark_exam_as_finished, then evaluate_results

on_data: what went out and what came back

on_data has two halves. The sending half records each outgoing picture with its true class. The two streams of the group carry a tag for every sample and the action keeps a pair only when the tags of the picture and of the class name match:

img_stream = self.get_stream(stream_group, data_type="img")
text_stream = self.get_stream(stream_group, data_type="text")
img_tag = img_stream.get_tag(uuid=uuid)
text_tag = text_stream.get_tag(uuid=uuid)
if img_tag is not None and img_tag == text_tag:
    img = img_stream.get("on_sending", uuid=uuid)
    text = text_stream.get("on_sending", uuid=uuid)
    if img is not None and text is not None:
        self.sent_samples[img_tag] = [img, text]

The first argument of get names the reader. Each reader receives a given sample only once and asking again returns None. The receiving half reads the processor stream of each student in the same way and stores the answer under the tag of the picture it refers to:

for student in self.current_students:
    student_stream = self.get_stream("processor", student, data_type="text")
    msg = student_stream.get("on_receiving", uuid=uuid)
    if msg is not None:
        tag = student_stream.get_tag(uuid=uuid)
        self.received_samples.setdefault(tag, {})[student] = msg

on_data returns True while samples move in either direction and for 25 seconds after the last sample sent (3 seconds in tutorial_steps/step4). The loop on exam_in_progress therefore keeps running as long as there is something to record. When it returns False, the machine tries the next transition (evaluate_results).

Scoring

src/teacher.py (evaluate_results, simplified)
@action
async def evaluate_results(self) -> bool:
    if not self.current_exam_finished:
        return False
    scores = {s: 0. for s in self.current_students}
    for tag, (_, truth) in self.sent_samples.items():
        for student, answer in self.received_samples.get(tag, {}).items():
            scores[student] += float(answer.strip().lower() == truth.strip().lower())
    for student in scores:
        scores[student] /= self.EXAM_SAMPLES
        old = self.student_quality.get(student)
        self.student_quality[student] = scores[student] if old is None else 0.5 * old + 0.5 * scores[student]
    for student, score in scores.items():
        await self.send(action_name="print", action_kwargs={"msg": f"🎯 Your exam result: **{score:.0%}**"},
                        from_state="in_class", target=student, volatile=True)
    return True

The score of a student is the fraction of correct answers. The quality index is a moving average of the scores that weighs the last exam and the previous history equally. The feedback stage of chapter 9 trusts only students whose quality index is at least 0.6. Each student receives its own score in a private notice.

Run it

Run tutorial_steps/step4 with the world, the teacher and both AI students. The teacher terminal shows the activity and a row of stars with the quality index of every student. After each exam it prints the answers of each student as a row of ✓, ✗ and · (no answer). The first exam comes after three lectures. Later rounds show how well the students keep the old classes while they learn the new ones.

Where next

The loop works with any number of students. Chapter 9 shows what the teacher does to keep it working when students come and go. It also shows how the teacher uses the class to improve its own material.

9 · The world master at work