-
Notifications
You must be signed in to change notification settings - Fork 0
/
train_store.py
1483 lines (1317 loc) · 55.1 KB
/
train_store.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Persists :py:class:`~scalarstop.datablob.DataBlob`,
:py:class:`~scalarstop.model_template.ModelTemplate`,
and :py:class:`~scalarstop.model.Model` metadata to a database.
What database should I use?
----------------------------
Currently the :py:class:`TrainStore` supports saving metadata
and metrics to either a SQLite or a PostgreSQL database.
If you are doing all of your work on a single machine, a
SQLite database is easier to set up. But if you are training machine
learning models on multiple machines, you should use a PostgreSQL
database instead of SQLite. The SQLite database is not optimal
for handling multiple concurrent writes.
How can I extend the :py:class:`TrainStore`?
--------------------------------------------
The :py:class:`TrainStore` does not implement absolutely every
type of query that you might want to perform on your
training metrics. However, we directly expose our SQLAlchemy
engine, connection, and tables in the :py:class:`TrainStore`
attributes :py:attr:`TrainStore.engine`,
:py:attr:`TrainStore.connection`, and
:py:attr:`TrainStore.table`.
"""
import dataclasses as _python_dataclasses
import datetime
import os
import sqlite3
import urllib.parse
from typing import Any, Dict, List, Literal, Optional, Sequence, Union
import alembic.command
import alembic.config
import alembic.migration
import alembic.operations
import pandas as pd
import sqlalchemy.dialects.postgresql
import sqlalchemy.dialects.sqlite
from log_with_context import Logger
from sqlalchemy import JSON as default_JSON
from sqlalchemy import (
Column,
DateTime,
ForeignKey,
Integer,
MetaData,
Table,
Text,
UniqueConstraint,
and_,
asc,
create_engine,
desc,
func,
)
from sqlalchemy import insert as default_insert
from sqlalchemy import inspect, select, text
from sqlalchemy.engine import Connection, Engine
from sqlalchemy.exc import IntegrityError
from scalarstop._datetime import utcnow
from scalarstop.datablob import DataBlobBase
from scalarstop.exceptions import SQLite_JSON_ModeDisabled
from scalarstop.hyperparams import enforce_dict, flatten_hyperparams
_LOGGER = Logger(__name__)
_ALEMBIC_SCRIPT_DIR = os.path.join(
os.path.dirname(os.path.dirname(__file__)), "alembic"
)
_TABLE_NAME_PREFIX = "scalarstop__"
_datablob_value_error = ValueError(
"You should not set both `datablob_name` and `datablob_group_name`. "
"Set `datablob_name` if you want to be more specific in your search "
"or set `datablob_group_name` if you want to be more general."
)
_model_template_value_error = ValueError(
"You should not set both `model_template_name` and `model_template_group_name`. "
"Set `model_template_name` if you want to be more specific in your search "
"or set `model_template_group_name` if you want to be more general."
)
_metric_direction_value_error = ValueError(
"Please provide both `metric_name` and `metric_direction` or neither."
)
@_python_dataclasses.dataclass(frozen=True)
class _ModelMetadata:
"""A dataclass to store :py:class:`TrainStore` metadata for a single :py:class:`~scalarstop.model.Model`.""" # pylint: disable=line-too-long
model_name: str
model_class_name: str
model_epoch_metrics: Dict[str, float]
model_last_modified: datetime.datetime
datablob_name: str
datablob_group_name: str
datablob_hyperparams: Dict[str, Any]
datablob_hyperparams_flat: Dict[str, Any]
model_template_name: str
model_template_group_name: str
model_template_hyperparams: Dict[str, Any]
sort_metric_name: str
sort_metric_value: float
def _enforce_list(value: Union[str, Sequence[Any]]) -> List[Any]:
if isinstance(value, str):
return [value]
return list(value)
def _censor_sqlalchemy_url_password(url: str) -> str:
"""
Returns a SQLAlchemy URL without the password.
Borrowed from https://github.com/WFT/aws-xray-sdk-python/blob/0134819b618962a201f6cb3453fdd24e412046a8/aws_xray_sdk/ext/sqlalchemy/util/decorators.py
""" # pylint: disable=line-too-long
u = urllib.parse.urlparse(url)
# Add Scheme to uses_netloc or // will be missing from url.
urllib.parse.uses_netloc.append(u.scheme)
safe_url = ""
if u.password is None:
safe_url = u.geturl()
else:
# Strip password from URL
host_info = u.netloc.rpartition("@")[-1]
parts = u._replace(netloc=f"{u.username}@{host_info}")
safe_url = parts.geturl()
return safe_url
def _sqlite_json_enabled() -> bool:
"""Return True if this Python installation supports SQLite3 JSON1."""
connection = sqlite3.connect(":memory:")
cursor = connection.cursor()
try:
cursor.execute('SELECT JSON(\'{"a": "b"}\')')
except sqlite3.OperationalError:
return False
cursor.close()
connection.close()
return True
def _flatten_hyperparam_results(results) -> List[Dict[str, str]]:
results_dicts = []
for row in results:
row_dict = dict(row)
dbh = row_dict.pop("datablob_hyperparams_flat")
if dbh is None:
dbh = row_dict.pop("datablob_hyperparams")
else:
row_dict.pop("datablob_hyperparams")
mth = row_dict.pop("model_template_hyperparams")
results_dicts.append(
dict(
**row_dict,
**{f"dbh__{key}": val for key, val in dbh.items()},
**{f"mth__{key}": val for key, val in mth.items()},
)
)
return results_dicts
class _TrainStoreTables:
"""Manages our :py:class:`sqlalchemy.schema.Table` objects."""
def __init__(self, table_name_prefix: str, dialect: str):
"""
Args:
table_name_prefix: A string prefix to add to all of
the table names we generate. This allows multiple
installations of ScalarStop to share the same
database.
dialect: The SQLAlchemy dialect that we are
constructing database tables for.
"""
if dialect == "postgresql":
JSON = getattr(sqlalchemy.dialects, dialect).JSONB
else:
JSON = default_JSON
self._table_name_prefix = table_name_prefix
self._metadata = MetaData()
self._datablob_table = Table(
self._table_name_prefix + "datablob",
self._metadata,
Column("datablob_name", Text, primary_key=True, nullable=False),
Column("datablob_group_name", Text, nullable=False),
Column("datablob_hyperparams", JSON, nullable=False),
Column(
"datablob_last_modified",
DateTime(timezone=True),
default=utcnow,
onupdate=utcnow,
nullable=False,
),
Column("datablob_hyperparams_flat", JSON, nullable=True),
extend_existing=True,
)
self._model_template_table = Table(
self._table_name_prefix + "model_template",
self._metadata,
Column("model_template_name", Text, primary_key=True, nullable=False),
Column("model_template_group_name", Text, nullable=False),
Column("model_template_hyperparams", JSON, nullable=False),
Column(
"model_template_last_modified",
DateTime(timezone=True),
default=utcnow,
onupdate=utcnow,
nullable=False,
),
extend_existing=True,
)
self._model_table = Table(
self._table_name_prefix + "model",
self._metadata,
Column("model_name", Text, primary_key=True, nullable=False),
Column("model_class_name", Text, nullable=False),
Column(
"model_last_modified",
DateTime(timezone=True),
default=utcnow,
onupdate=utcnow,
nullable=False,
),
Column(
"datablob_name",
Text,
ForeignKey(
self._datablob_table.c.datablob_name,
onupdate="CASCADE",
ondelete="CASCADE",
),
nullable=False,
),
Column(
"model_template_name",
Text,
ForeignKey(
self._model_template_table.c.model_template_name,
onupdate="CASCADE",
ondelete="CASCADE",
),
nullable=False,
),
extend_existing=True,
)
self._model_epoch_table = Table(
self._table_name_prefix + "model_epoch",
self._metadata,
Column(
"model_epoch_id",
Integer,
primary_key=True,
autoincrement=True,
nullable=False,
),
Column("model_epoch_num", Integer, nullable=False),
Column(
"model_name",
Text,
ForeignKey(
self._model_table.c.model_name,
onupdate="CASCADE",
ondelete="CASCADE",
),
nullable=False,
),
Column("model_epoch_metrics", JSON, nullable=False),
Column(
"model_epoch_last_modified",
DateTime(timezone=True),
default=utcnow,
onupdate=utcnow,
nullable=False,
),
Column("steps_per_epoch", Integer, nullable=True),
Column("validation_steps_per_epoch", Integer, nullable=True),
UniqueConstraint("model_epoch_num", "model_name"),
extend_existing=True,
)
@property
def metadata(self):
"""The :py:class:`sqlalchemy.sql.schema.MetaData` for this database connection."""
return self._metadata
@property
def datablob(self) -> Table:
"""
The :py:class:`sqlalchemy.schema.Table` used to store
:py:class:`~scalarstop.DataBlob` objects.
"""
return self._datablob_table
@property
def model_template(self) -> Table:
"""
The :py:class:`sqlalchemy.schema.Table`used to store
:py:class:`~scalarstop.ModelTemplate` objects.
"""
return self._model_template_table
@property
def model(self) -> Table:
"""
The :py:class:`sqlalchemy.schema.Table` used to store
:py:class:`~scalarstop.model.Model` objects.
"""
return self._model_table
@property
def model_epoch(self) -> Table:
"""
The :py:class:`sqlalchemy.schema.Table` used to store
metrics from model epochs.
"""
return self._model_epoch_table
class TrainStore:
"""Loads and saves names, hyperparameters, and training metrics from :py:class:`~scalarstop.datablob.DataBlob`, :py:class:`~scalarstop.model_template.ModelTemplate`, and :py:class:`~scalarstop.model.Model` objects.""" # pylint: disable=line-too-long
@classmethod
def from_filesystem(
cls,
*,
filename: str,
table_name_prefix: Optional[str] = None,
echo: bool = False,
) -> "TrainStore":
"""
Use a SQLite3 database file on the local filesystem as the train store.
Args:
filename: The filename of the SQLite3 file.
table_name_prefix: A string prefix to add to all of
the table names we generate. This allows multiple
installations of ScalarStop to share the same
database.
echo: Set to ``True`` to print out the SQL statements
that the :py:class:`TrainStore` executes.
"""
return cls(
connection_string="sqlite:///" + filename,
table_name_prefix=table_name_prefix,
echo=echo,
)
def __init__(
self,
connection_string: str,
*,
table_name_prefix: Optional[str] = None,
echo: bool = False,
):
"""
Create a :py:class:`TrainStore` instance connected to
an external database.
Use this constructor if you want to connect to
a PostgreSQL database. If you want to use a SQLite file as the database,
you should instead use the :py:meth:`TrainStore.from_filesystem`
classmethod.
Args:
connection_string: A SQLAlchemy database connection
string for connecting to a database. A typical
PostgreSQL connection string looks like
``"postgresql://username:password@hostname:port/database"``,
with the ``port`` defaulting to ``5432``.
table_name_prefix: A string prefix to add to all of
the table names we generate. This allows multiple
installations of ScalarStop to share the same
database.
echo: Set to ``True`` to print out the SQL statements
that the :py:class:`TrainStore` executes.
"""
# The `postgres://` connection prefix is deprecated after
# SQLAlchemy 1.4. We'll do the find-and-replace on the user's
# behalf.
if connection_string.startswith("postgres://"):
connection_string = connection_string.replace(
"postgres://", "postgresql://", 1
)
self._connection_string = connection_string
self._connection_string_no_password = _censor_sqlalchemy_url_password(
self._connection_string
)
self._table_name_prefix = table_name_prefix or _TABLE_NAME_PREFIX
self._echo = echo
self._engine = create_engine(
self._connection_string,
echo=self._echo,
future=True,
)
self._connection = self._engine.connect()
if self._engine.name == "sqlite":
if not _sqlite_json_enabled():
raise SQLite_JSON_ModeDisabled()
with self._connection.begin():
self._connection.execute(text("PRAGMA foreign_keys = ON"))
self._table = _TrainStoreTables(
table_name_prefix=self._table_name_prefix, dialect=self._engine.name
)
# Create all of the database columns at once.
with self._connection.begin():
# Create the database tables if they do not exist.
# But do not add columns or alter tables that already exist.
self._table.metadata.create_all(bind=self._engine)
# Set up the inspector so we can csee if create_all()
# didn't create all of the columns that we wanted.
inspector = inspect(self._connection)
# Configure Alembic so we can manually add columns
# in this database transaction.
context = alembic.migration.MigrationContext.configure(self._connection)
op = alembic.operations.Operations(context)
# Iterate over the ScalarStop database tables,
# manually adding any database columns that happen to be missing.
for table_name, expected_table in self._table.metadata.tables.items():
actual_column_names = {
col["name"] for col in inspector.get_columns(table_name)
}
for expected_col in expected_table.columns:
if expected_col.name not in actual_column_names:
_LOGGER.warning(
"Manually creating the new database column "
f"`{table_name}.{expected_col.name}`."
)
op.add_column(table_name, expected_col) # type: ignore
def __repr__(self) -> str:
return f"<sp.TrainStore {self._connection_string_no_password}>"
@property
def table(self) -> _TrainStoreTables:
"""
References to the :py:class:`sqlalchemy.schema.Table` objects
representing our database tables.
Currently, there are four tables that are attributes to this
property:
* ``datablob``
* ``model_template``
* ``model``
* ``model_epoch``
"""
return self._table
@property
def engine(self) -> Engine:
"""
The currently active :py:class:`sqlalchemy.engine.Engine`.
This is useful if you want to write custom SQLAlchemy
code on top of :py:class:`TrainStore`.
"""
return self._engine
@property
def connection(self) -> Connection:
"""
The currently active :py:class:`sqlalchemy.engine.Connection`.
This is useful if you want to write custom SQLAlchemy
code on top of :py:class:`TrainStore`.
"""
return self._connection
def _insert(
self, *, table, values, index_elements=None, ignore_existing: bool
) -> None:
if ignore_existing:
if self._engine.name == "sqlite":
with self.connection.begin():
self.connection.execute(
sqlalchemy.dialects.sqlite.insert(table)
.values(**values)
.on_conflict_do_nothing(index_elements=index_elements)
)
elif self._engine.name == "postgresql":
with self.connection.begin():
self.connection.execute(
sqlalchemy.dialects.postgresql.insert(table)
.values(**values)
.on_conflict_do_nothing(index_elements=index_elements)
)
else:
try:
with self.connection.begin():
self.connection.execute(default_insert(table).values(**values))
except IntegrityError:
_LOGGER.info("Suppressed IntegrityError", exc_info=True)
else:
with self.connection.begin():
self.connection.execute(default_insert(table).values(**values))
def _as_pandas(self, stmt) -> pd.DataFrame:
with self.connection.begin():
return pd.read_sql_query(sql=stmt, con=self.connection)
def insert_datablob(
self, datablob: DataBlobBase, *, ignore_existing: bool = False
) -> None:
"""
Logs the :py:class:`~scalarstop.datablob.DataBlob` name, group name,
and hyperparams to the :py:class:`TrainStore`.
This also supports inserting other subclasses of
:py:class:`~scalarstop.datablob.DataBlobBase`, such as
:py:class:`~scalarstop.datablob.DistributedDataBlob`.
Args:
datablob: A :py:class:`~scalarstop.datablob.DataBlob`
instance whose name and hyperparameters that
we want to record in the database.
ignore_existing: Set this to ``True`` to ignore
if a :py:class:`~scalarstop.datablob.DataBlob`
with the same name is already in the database,
in which case this function will do nothing.
Note that :py:class:`~scalarstop.datablob.DataBlob`
instances are supposed to be immutable, so
:py:class:`TrainStore` does not implement
updating them.
"""
self.insert_datablob_by_str(
name=datablob.name,
group_name=datablob.group_name,
hyperparams=datablob.hyperparams,
ignore_existing=ignore_existing,
)
def insert_datablob_by_str(
self,
*,
name: str,
group_name: str,
hyperparams: Any,
ignore_existing: bool = False,
):
"""
Logs the :py:class:`~scalarstop.datablob.DataBlob` name, group
name, and hyperparams to the :py:class:`TrainStore`.
Args:
name: Your :py:class:`~scalarstop.datablob.DataBlob`
name.
group_name: Your :py:class:`~scalarstop.datablob.DataBlob`
group name.
hyperparams: Your :py:class:`~scalarstop.datablob.DataBlob`
hyperparameters.
ignore_existing: Set this to ``True`` to ignore
if a :py:class:`~scalarstop.datablob.DataBlob`
with the same name is already in the database,
in which case this function will do nothing.
Note that :py:class:`~scalarstop.datablob.DataBlob`
instances are supposed to be immutable, so
:py:class:`TrainStore` does not implement
updating them.
"""
values = dict(
datablob_name=name,
datablob_group_name=group_name,
datablob_hyperparams=enforce_dict(hyperparams),
datablob_hyperparams_flat=flatten_hyperparams(hyperparams),
)
self._insert(
table=self.table.datablob,
values=values,
index_elements=[self.table.datablob.c.datablob_name],
ignore_existing=ignore_existing,
)
def _query_datablob_stmt(
self,
*,
datablob_name: Optional[Union[str, Sequence[str]]] = None,
datablob_group_name: Optional[Union[str, Sequence[str]]] = None,
):
stmt = select(
[
self.table.datablob.c.datablob_name.label("name"),
self.table.datablob.c.datablob_group_name.label("group_name"),
self.table.datablob.c.datablob_hyperparams.label("hyperparams"),
self.table.datablob.c.datablob_hyperparams_flat.label(
"hyperparams_flat"
),
self.table.datablob.c.datablob_last_modified.label("last_modified"),
]
).select_from(self.table.datablob)
if datablob_name and datablob_group_name:
raise _datablob_value_error
if datablob_name:
stmt = stmt.where(
self.table.datablob.c.datablob_name.in_(_enforce_list(datablob_name))
)
elif datablob_group_name:
stmt = stmt.where(
self.table.datablob.c.datablob_group_name.in_(
_enforce_list(datablob_group_name)
)
)
stmt = stmt.order_by(self.table.datablob.c.datablob_last_modified)
return stmt
def list_datablobs(
self,
*,
datablob_name: Optional[Union[str, Sequence[str]]] = None,
datablob_group_name: Optional[Union[str, Sequence[str]]] = None,
) -> pd.DataFrame:
"""
Returns a :py:class:`pandas.DataFrame` listing the
:py:class:`~scalarstop.datablob.DataBlob` names in the database.
If you call this method without any arguments, it will list
ALL of the :py:class:`~scalarstop.datablob.DataBlob` s in
the database. You can narrow down your results by providing
ONE (but not both) of the below arguments.
Args:
datablob_name: Either a single :py:class:`~scalarstop.datablob.DataBlob`
name or a list of names to select.
datablob_group_name: Either a single :py:class:`~scalarstop.datablob.DataBlob`
group name or a list of group names to select.
"""
return self._as_pandas(
self._query_datablob_stmt(
datablob_name=datablob_name, datablob_group_name=datablob_group_name
)
)
def insert_model_template(self, model_template, *, ignore_existing: bool = False):
"""
Logs the :py:class:`~scalarstop.model_template.ModelTemplate`
name, group name, and hyperparams to the :py:class:`TrainStore`.
Args:
model_template: A :py:class:`~scalarstop.model_template.ModelTemplate`
instance whose name and hyperparameters that
we want to record in the database.
ignore_existing: Set this to ``True`` to ignore
if a :py:class:`~scalarstop.model_template.ModelTemplate`
with the same name is already in the database,
in which case this function will do nothing.
Note that :py:class:`~scalarstop.model_template.ModelTemplate`
instances are supposed to be immutable, so
:py:class:`TrainStore` does not implement
updating them.
"""
self.insert_model_template_by_str(
name=model_template.name,
group_name=model_template.group_name,
hyperparams=model_template.hyperparams,
ignore_existing=ignore_existing,
)
def insert_model_template_by_str(
self, *, name: str, group_name: str, hyperparams, ignore_existing: bool = False
):
"""
Logs the :py:class:`~scalarstop.model_template.ModelTemplate`
name, group name, and hyperparams to the :py:class:`TrainStore`.
Args:
name: Your :py:class:`~scalarstop.model_template.ModelTemplate`
name.
group_name: Your :py:class:`~scalarstop.model_template.ModelTemplate`
group name.
hyperparams: Your :py:class:`~scalarstop.model_template.ModelTemplate`
hyperparameters.
ignore_existing: Set this to ``True`` to ignore
if a :py:class:`~scalarstop.model_template.ModelTemplate`
with the same name is already in the database,
in which case this function will do nothing.
Note that :py:class:`~scalarstop.model_template.ModelTemplate`
instances are supposed to be immutable, so
:py:class:`TrainStore` does not implement
updating them.
"""
values = dict(
model_template_name=name,
model_template_group_name=group_name,
model_template_hyperparams=enforce_dict(hyperparams),
)
self._insert(
table=self.table.model_template,
values=values,
index_elements=[self.table.model_template.c.model_template_name],
ignore_existing=ignore_existing,
)
def _query_model_template_stmt(
self,
*,
model_template_name: Optional[Union[str, Sequence[str]]] = None,
model_template_group_name: Optional[Union[str, Sequence[str]]] = None,
):
stmt = select(
[
self.table.model_template.c.model_template_name.label("name"),
self.table.model_template.c.model_template_group_name.label(
"group_name"
),
self.table.model_template.c.model_template_hyperparams.label(
"hyperparams"
),
self.table.model_template.c.model_template_last_modified.label(
"last_modified"
),
]
).select_from(self.table.model_template)
if model_template_name and model_template_group_name:
raise _model_template_value_error
if model_template_name:
stmt = stmt.where(
self.table.model_template.c.model_template_name.in_(
_enforce_list(model_template_name)
)
)
elif model_template_group_name:
stmt = stmt.where(
self.table.model_template.c.model_template_group_name.in_(
_enforce_list(model_template_group_name)
)
)
stmt = stmt.order_by(self.table.model_template.c.model_template_last_modified)
return stmt
def list_model_templates(
self,
*,
model_template_name: Optional[Union[str, Sequence[str]]] = None,
model_template_group_name: Optional[Union[str, Sequence[str]]] = None,
):
"""
Returns a :py:class:`pandas.DataFrame` listing ALL of the rows in the
:py:class:`~scalarstop.model_template.ModelTemplate` table.
If you call this method without any arguments, it will list
ALL of the :py:class:`~scalarstop.model_template.ModelTemplate` s in
the database. You can narrow down your results by providing
ONE (but not both) of the below arguments.
Args:
model_template_name: Either a single
:py:class:`~scalarstop.model_template.ModelTemplate`
name or a list of names to select.
model_template_group_name: Either a single
:py:class:`~scalarstop.model_template.ModelTemplate`
group name or a list of group names to select.
"""
return self._as_pandas(
self._query_model_template_stmt(
model_template_name=model_template_name,
model_template_group_name=model_template_group_name,
)
)
def insert_model(self, model, *, ignore_existing: bool = False):
"""
Logs the :py:class:`~scalarstop.model.Model` name,
:py:class:`~scalarstop.datablob.DataBlob`, and
:py:class;`~scalarstop.model_template.ModelTemplate`
to the :py:class:`TrainStore`.
Args:
model: A :py:class:`~scalarstop.model.Model`
instance whose name and hyperparameters that
we want to record in the database.
ignore_existing: Set this to ``True`` to ignore
if a :py:class:`~scalarstop.model.Model`
with the same name is already in the database,
in which case this function will do nothing.
The :py:class:`TrainStore` does not implement
the updating of :py:class:`~scalarstop.model.Model`
name or hyperparameters. The only way to change
a :py:class:`~scalarstop.model.Model` is to
log more epochs.
"""
self.insert_model_by_str(
name=model.name,
model_class_name=model.__class__.__name__,
datablob_name=model.datablob.name,
model_template_name=model.model_template.name,
ignore_existing=ignore_existing,
)
def insert_model_by_str(
self,
*,
name: str,
model_class_name: str,
datablob_name: str,
model_template_name: str,
ignore_existing: bool = False,
) -> None:
"""
Logs the :py:class:`~scalarstop.model.Model` name,
:py:class:`~scalarstop.datablob.DataBlob`, and
:py:class;`~scalarstop.model_template.ModelTemplate`
to the :py:class:`TrainStore`.
Args:
name: The :py:class:`~scalarstop.model.Model` name.
model_class_name: The :py:class:`~scalarstop.model.Model`
subclass name used. If you are using
:py:class:`~scalarstop.model.KerasModel`,
then this value is the string ``"KerasModel"``.
datablob_name: The :py:class:`~scalarstop.datablob.DataBlob`
name used to create the :py:class:`~scalarstop.model.Model`
instance.
model_template_name: The
:py:class:`~scalarstop.model_template.ModelTemplate`
name used to create the :py:class:`~scalarstop.model.Model`
instance.
ignore_existing: Set this to ``True`` to ignore
if a :py:class:`~scalarstop.model.Model`
with the same name is already in the database,
in which case this function will do nothing.
The :py:class:`TrainStore` does not implement
the updating of :py:class:`~scalarstop.model.Model`
name or hyperparameters. The only way to change
a :py:class:`~scalarstop.model.Model` is to
log more epochs.
"""
values = dict(
model_name=name,
model_class_name=model_class_name,
datablob_name=datablob_name,
model_template_name=model_template_name,
)
self._insert(
table=self.table.model,
values=values,
index_elements=[self.table.model.c.model_name],
ignore_existing=ignore_existing,
)
def _query_model_stmt(
self,
*,
datablob_name: Optional[Union[str, Sequence[str]]] = None,
datablob_group_name: Optional[Union[str, Sequence[str]]] = None,
model_template_name: Optional[Union[str, Sequence[str]]] = None,
model_template_group_name: Optional[Union[str, Sequence[str]]] = None,
):
where_conditions = []
if datablob_name and datablob_group_name:
raise _datablob_value_error
if datablob_name:
where_conditions.append(
self.table.datablob.c.datablob_name.in_(_enforce_list(datablob_name))
)
elif datablob_group_name:
where_conditions.append(
self.table.datablob.c.datablob_group_name.in_(
_enforce_list(datablob_group_name)
)
)
if model_template_name and model_template_group_name:
raise _model_template_value_error
if model_template_name:
where_conditions.append(
self.table.model_template.c.model_template_name.in_(
_enforce_list(model_template_name)
)
)
elif model_template_group_name:
where_conditions.append(
self.table.model_template.c.model_template_group_name.in_(
_enforce_list(model_template_group_name)
)
)
stmt = (
select(
[
self.table.model.c.model_name,
self.table.model.c.model_class_name,
self.table.model.c.model_last_modified,
self.table.datablob.c.datablob_name,
self.table.datablob.c.datablob_group_name,
self.table.datablob.c.datablob_hyperparams,
self.table.datablob.c.datablob_hyperparams_flat,
self.table.model_template.c.model_template_name,
self.table.model_template.c.model_template_group_name,
self.table.model_template.c.model_template_hyperparams,
]
)
.select_from(self.table.model)
.join(
self.table.datablob,
self.table.model.c.datablob_name == self.table.datablob.c.datablob_name,
)
.join(
self.table.model_template,
self.table.model.c.model_template_name
== self.table.model_template.c.model_template_name,
)
)
if where_conditions:
stmt = stmt.where(and_(*where_conditions))
stmt = stmt.order_by(self.table.model.c.model_last_modified)
return stmt
def _query_model_by_epoch_stmt(
self,
*,
metric_name: Optional[str] = None,
metric_direction: Optional[str] = None,
datablob_name: Optional[Union[str, Sequence[str]]] = None,
datablob_group_name: Optional[Union[str, Sequence[str]]] = None,
model_template_name: Optional[Union[str, Sequence[str]]] = None,
model_template_group_name: Optional[Union[str, Sequence[str]]] = None,
limit: Optional[int] = None,
return_other_metrics: bool = True,
):
where_conditions = []
if datablob_name and datablob_group_name:
raise _datablob_value_error
if datablob_name:
where_conditions.append(
self.table.datablob.c.datablob_name.in_(_enforce_list(datablob_name))
)
elif datablob_group_name:
where_conditions.append(
self.table.datablob.c.datablob_group_name.in_(
_enforce_list(datablob_group_name)
)
)
if model_template_name and model_template_group_name:
raise _model_template_value_error
if model_template_name:
where_conditions.append(
self.table.model_template.c.model_template_name.in_(
_enforce_list(model_template_name)
)
)
elif model_template_group_name:
where_conditions.append(
self.table.model_template.c.model_template_group_name.in_(
_enforce_list(model_template_group_name)
)
)
columns = [
self.table.model.c.model_name,
self.table.model.c.model_class_name,
self.table.model.c.model_last_modified,
self.table.datablob.c.datablob_name,
self.table.datablob.c.datablob_group_name,
self.table.datablob.c.datablob_hyperparams,
self.table.datablob.c.datablob_hyperparams_flat,
self.table.model_template.c.model_template_name,
self.table.model_template.c.model_template_group_name,
self.table.model_template.c.model_template_hyperparams,
]
if return_other_metrics: