ihatebaselines commited on
Commit
6d13da1
Β·
verified Β·
1 Parent(s): e610a72

Add full SocrateX API directly on SOCRATE class (create_config, new, make_trainer, generate_data, load_data)

Browse files
Files changed (1) hide show
  1. model.py +143 -9
model.py CHANGED
@@ -296,17 +296,151 @@ class SOCRATE(PreTrainedModel):
296
  param.requires_grad = True
297
  print("Encoder has been unfrozen.")
298
 
299
- def summary(self):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
300
  """
301
- Prints a summary of the model's parameters.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
302
  """
303
- total_params = sum(p.numel() for p in self.parameters())
304
- trainable_params = sum(p.numel() for p in self.parameters() if p.requires_grad)
305
- print(f"=== SOCRATE Model Summary ===")
306
- print(f"Total parameters: {total_params / 1e6:.2f} M")
307
- print(f"Trainable parameters: {trainable_params / 1e6:.2f} M")
308
- print(f"d_model: {self.d_model}")
309
- print("=============================")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
310
 
311
  # Factory functions for models
312
 
 
296
  param.requires_grad = True
297
  print("Encoder has been unfrozen.")
298
 
299
+ # ──────────────────────────────────────────────────────────────────────────
300
+ # Class-level API β€” everything SocrateX can do, directly on the model
301
+ # ──────────────────────────────────────────────────────────────────────────
302
+
303
+ @staticmethod
304
+ def create_config(
305
+ d_model=256,
306
+ nhead=4,
307
+ num_layers=4,
308
+ dim_feedforward=1024,
309
+ activation="gelu",
310
+ norm_first=True,
311
+ max_len=512,
312
+ pool_height=4,
313
+ ):
314
  """
315
+ Create a custom architecture config without needing to import SocrateX separately.
316
+
317
+ Example::
318
+
319
+ model = AutoModel.from_pretrained("ihatebaselines/Socrate", trust_remote_code=True)
320
+ cfg = model.create_config(d_model=512, nhead=8, num_layers=6, dim_feedforward=2048)
321
+ tok = model.make_tokenizer()
322
+ new_model = model.new(config=cfg, tokenizer=tok)
323
+ """
324
+ from configuration_socrate import SocrateConfig
325
+ return SocrateConfig(
326
+ d_model=d_model,
327
+ nhead=nhead,
328
+ num_layers=num_layers,
329
+ dim_feedforward=dim_feedforward,
330
+ activation=activation,
331
+ norm_first=norm_first,
332
+ max_len=max_len,
333
+ pool_height=pool_height,
334
+ )
335
+
336
+ @staticmethod
337
+ def make_tokenizer(path=None):
338
+ """
339
+ Initialize a fresh BPE tokenizer from scratch, or load one from a file.
340
+
341
+ Example::
342
+
343
+ tok = model.make_tokenizer() # fresh tokenizer
344
+ tok = model.make_tokenizer("ocr_bpe_tokenizer.json") # load from file
345
+ """
346
+ if path is not None:
347
+ from tokenizers import Tokenizer
348
+ return Tokenizer.from_file(path)
349
+ try:
350
+ from tokenizer import init_tokenizer
351
+ except ImportError:
352
+ from SocrateX.tokenizer import init_tokenizer
353
+ return init_tokenizer()
354
+
355
+ @classmethod
356
+ def new(cls, config, tokenizer, device="cuda"):
357
+ """
358
+ Build a brand-new SOCRATE model from a config + tokenizer.
359
+ No pretrained weights β€” starts from scratch.
360
+
361
+ Example::
362
+
363
+ cfg = model.create_config(d_model=256, nhead=4, num_layers=4, dim_feedforward=1024)
364
+ tok = model.make_tokenizer()
365
+ my_model = model.new(config=cfg, tokenizer=tok, device="cpu")
366
+ print(my_model.summary())
367
+ """
368
+ import torch
369
+ hf_config = cls.create_config(
370
+ d_model=config.d_model if hasattr(config, 'd_model') else 256,
371
+ nhead=config.nhead if hasattr(config, 'nhead') else 4,
372
+ num_layers=config.num_layers if hasattr(config, 'num_layers') else 4,
373
+ dim_feedforward=config.dim_feedforward if hasattr(config, 'dim_feedforward') else 1024,
374
+ )
375
+ hf_config.vocab_size = tokenizer.get_vocab_size()
376
+ hf_config.pad_id = tokenizer.token_to_id("<pad>")
377
+ hf_config.bos_id = tokenizer.token_to_id("<bos>")
378
+ hf_config.eos_id = tokenizer.token_to_id("<eos>")
379
+ return cls(hf_config, tokenizer=tokenizer, sx_config=config).to(device)
380
+
381
+ def make_trainer(self, dataloader, optimizer, criterion, device=None):
382
  """
383
+ Returns a Trainer object wired to this model.
384
+
385
+ Example::
386
+
387
+ loader = model.make_dataset(images, labels).to_loader(batch_size=16)
388
+ opt = torch.optim.AdamW(model.parameters(), lr=1e-4)
389
+ crit = torch.nn.CrossEntropyLoss()
390
+ trainer = model.make_trainer(loader, opt, crit)
391
+ for epoch in range(50):
392
+ loss = trainer.train_epoch()
393
+ """
394
+ try:
395
+ from trainer import Trainer
396
+ except ImportError:
397
+ from SocrateX.trainer import Trainer
398
+ _device = device or ("cuda" if __import__("torch").cuda.is_available() else "cpu")
399
+ return Trainer(self, dataloader, optimizer, criterion, device=_device)
400
+
401
+ def generate_data(self, source, count=1000, output_dir="silly_train", mode="train"):
402
+ """
403
+ Generate a quick synthetic dataset directly from the model object.
404
+
405
+ Args:
406
+ source: URL or file path with words to render
407
+ count: number of images to generate
408
+ output_dir: folder to save images + labels.csv
409
+ mode: 'train' or 'test'
410
+
411
+ Example::
412
+
413
+ model.generate_data(
414
+ source="https://raw.githubusercontent.com/.../google-10000-english.txt",
415
+ count=500,
416
+ output_dir="my_data",
417
+ mode="train"
418
+ )
419
+ """
420
+ try:
421
+ from synthetic import generate_silly_training_set, generate_silly_testing_set
422
+ except ImportError:
423
+ from SocrateX.synthetic import generate_silly_training_set, generate_silly_testing_set
424
+ if mode == "train":
425
+ return generate_silly_training_set(source=source, count=count, output_dir=output_dir)
426
+ else:
427
+ return generate_silly_testing_set(source=source, count=count, output_dir=output_dir)
428
+
429
+ def load_data(self, path):
430
+ """
431
+ Load a dataset from a CSV / JSON / TXT file.
432
+ Returns (images, labels).
433
+
434
+ Example::
435
+
436
+ images, labels = model.load_data("label.csv")
437
+ dataset = model.make_dataset(images, labels)
438
+ """
439
+ try:
440
+ from dataset import load_dataset
441
+ except ImportError:
442
+ from SocrateX.dataset import load_dataset
443
+ return load_dataset(path)
444
 
445
  # Factory functions for models
446