Schema-Aware Neural Architectures for Structured Data
Most deep learning code receives its input as tensors with no record of what each column or index means. For images that is often enough, because the inductive bias of convolution carries much of the work. For structured data (relational tables, knowledge graphs, scientific records) the schema carries information that the model and the pipeline around it can use directly.
This article is about schema awareness as a design principle for neural architectures on structured data.
A note on the name in this page's address: NeuroSchemaX is also a separate, released package, available on PyPI (pip install neuroschemax, Python 3.11 or newer) with its source on GitHub. It is a neural network architecture visualization and export toolkit built on NN-SVG: according to its documentation, it parses model definitions (ONNX, PyTorch, TensorFlow, JSON or YAML) and renders architecture diagrams. It does not do schema-aware encoding of structured data, which is the subject of this article. Version 0.1.6, marked Alpha, was the latest release when checked on 26 November 2026. TGraphX 1.5.1 neither includes nor requires it, and everything below is plain PyTorch and TGraphX. Examples tested with TGraphX 1.5.1.
The structured data problem
A relational record has named fields with known types: patient_id (identifier), age (integer, range 0-120), diagnosis (categorical, from a known vocabulary), notes (text). A neural pipeline can treat them in three ways:
- One-hot encode and concatenate. The type information is used once, during preprocessing. Field names, ranges and references are not visible to the model.
- Per-field embeddings. Better, but nothing says that two fields share a vocabulary, that one has a range constraint or that one references another table.
- Schema-aware encoding. Keep the schema as data. Use it to build the model, validate inputs and restrict outputs.
The third option is not new in spirit. The work lies in applying it consistently.
What schema awareness buys
Inductive bias. If two fields draw from the same vocabulary, they can share embedding parameters. This is a modelling choice to test, not a guaranteed gain.
Validation. The schema that drives the encoder can also report which field of which record violates which constraint. That happens in the data pipeline, before the network sees anything.
Explainability. When each field keeps its own inputs up to a known point in the network, attributing a prediction to a field is easier than attributing it to dimensions of a mixed embedding.
Constrained outputs. A model that generates or ranks structured outputs can be restricted to values the schema allows. The guarantee comes from masking or constrained decoding, not from showing the schema to the model.
A schema that drives the model
Here the schema is a plain dictionary. It decides both what counts as a valid record and how the encoder is built. Two fields refer to the same vocabulary, so they share one embedding table.
import torch
import torch.nn as nn
VOCABULARIES = {"diagnosis": ["none", "asthma", "diabetes", "hypertension"]}
SCHEMA = {
"age": {"type": "numeric", "min": 0, "max": 120},
"primary_dx": {"type": "categorical", "vocabulary": "diagnosis"},
"secondary_dx": {"type": "categorical", "vocabulary": "diagnosis"},
}
def validate(record):
problems = []
for name, spec in SCHEMA.items():
value = record.get(name)
if value is None:
problems.append(f"{name}: missing")
elif spec["type"] == "numeric":
if not isinstance(value, (int, float)) or not spec["min"] <= value <= spec["max"]:
problems.append(f"{name}: {value!r} is not a number in the declared range")
elif value not in VOCABULARIES[spec["vocabulary"]]:
problems.append(f"{name}: {value!r} is not in vocabulary {spec['vocabulary']!r}")
problems += [f"{name}: not in the schema" for name in record if name not in SCHEMA]
return problems
class SchemaEncoder(nn.Module):
"""One scaled input per numeric field, one embedding table per vocabulary."""
def __init__(self, schema, vocabularies, dim=8, out_dim=16):
super().__init__()
self.schema, self.vocabularies = schema, vocabularies
self.tables = nn.ModuleDict(
{name: nn.Embedding(len(words), dim) for name, words in vocabularies.items()})
width = sum(1 if spec["type"] == "numeric" else dim for spec in schema.values())
self.mix = nn.Linear(width, out_dim)
def forward(self, records):
parts = []
for name, spec in self.schema.items():
if spec["type"] == "numeric":
span = spec["max"] - spec["min"]
parts.append(torch.tensor([[(r[name] - spec["min"]) / span] for r in records],
dtype=torch.float))
else:
words = self.vocabularies[spec["vocabulary"]]
ids = torch.tensor([words.index(r[name]) for r in records])
parts.append(self.tables[spec["vocabulary"]](ids))
return self.mix(torch.cat(parts, dim=1))
records = [
{"age": 54, "primary_dx": "diabetes", "secondary_dx": "hypertension"},
{"age": 430, "primary_dx": "asthma", "secondary_dx": "gout"},
]
for record in records:
print(validate(record))
# []
# ['age: 430 is not a number in the declared range', "secondary_dx: 'gout' is not in vocabulary 'diagnosis'"]
torch.manual_seed(0)
encoder = SchemaEncoder(SCHEMA, VOCABULARIES)
valid = [record for record in records if not validate(record)]
print(tuple(encoder(valid).shape), len(encoder.tables)) # (1, 16) 1
The encoder does not check ranges (an age of 430 would simply be scaled), so call validate first. It also requires every field, so optional values would need an explicit missing-value category or mask.
Where this connects to TGraphX
A knowledge graph is a particularly clean structured-data domain. Entities have types, relations have signatures (which entity types they connect), and constraints such as "a person has only one date of birth" are part of the schema.
TGraphX's knowledge graph subsystem, tgraphx.kg, provides building blocks:
KnowledgeGraph, which can store anentity_typestensor.TypedNegativeSampler, which draws corrupted heads and tails from per-relationdomainsandranges.MultimodalKGModelwith entity projectors, one per modality (vectors, images, precomputed text vectors).LogicalConstraintChecker(Experimental), which reports symmetric, antisymmetric and inverse-relation violations among the stored triples.
It does not provide a schema language. KnowledgeGraph stores the types but does not check triples against them, and the constraint checker looks at neither entity types nor cardinality (its docstring also lists domain and range violations, which 1.5.1 does not implement). Signature and cardinality checks are your code.
Typed entities and relation signatures
import tgraphx as tgx
from tgraphx.kg import LogicalConstraintChecker, TypedNegativeSampler
ENTITY_TYPES = {"user": 0, "movie": 1}
RELATIONS = ["rated", "sequel_of"] # list position = relation ID
SIGNATURES = {"rated": ("user", "movie"), "sequel_of": ("movie", "movie")}
num_users, num_movies = 6, 8
num_entities = num_users + num_movies # users are 0-5, movies 6-13
entity_types = torch.tensor([0] * num_users + [1] * num_movies)
triples = torch.tensor([[0, 0, 6], [0, 0, 7], [1, 0, 7], [2, 0, 9], [3, 0, 10],
[4, 0, 12], [5, 0, 13], [7, 1, 6], [9, 1, 8]])
kg = tgx.KnowledgeGraph(triples, num_entities=num_entities, num_relations=len(RELATIONS),
entity_types=entity_types, entity_type_to_id=ENTITY_TYPES)
def signature_errors(triples):
errors = []
for h, r, t in triples.tolist():
head_type, tail_type = SIGNATURES[RELATIONS[r]]
if (entity_types[h] != ENTITY_TYPES[head_type]
or entity_types[t] != ENTITY_TYPES[tail_type]):
errors.append((h, r, t))
return errors
assert signature_errors(kg.triples) == []
print(signature_errors(torch.tensor([[6, 0, 0]]))) # [(6, 0, 0)]: a movie "rates" a user
# Cardinality rule: a movie is the sequel of at most one movie.
sequel_heads = kg.triples[kg.triples[:, 1] == RELATIONS.index("sequel_of"), 0]
assert sequel_heads.unique().numel() == sequel_heads.numel()
# Logical rule: sequel_of is antisymmetric. Add a contradicting triple and check.
SEQUEL = RELATIONS.index("sequel_of")
broken = tgx.KnowledgeGraph(torch.cat([triples, torch.tensor([[6, SEQUEL, 7]])]),
num_entities=num_entities, num_relations=len(RELATIONS))
found = LogicalConstraintChecker(broken, antisymmetric_relations={SEQUEL}).check_all()
print([v.triple_a for v in found["antisymmetric"]]) # [(7, 1, 6), (6, 1, 7)]
members = {name: set((entity_types == i).nonzero().flatten().tolist())
for name, i in ENTITY_TYPES.items()}
domains = {r: members[SIGNATURES[name][0]] for r, name in enumerate(RELATIONS)}
ranges = {r: members[SIGNATURES[name][1]] for r, name in enumerate(RELATIONS)}
sampler = TypedNegativeSampler(num_entities, num_negatives=4, domains=domains, ranges=ranges)
negatives = sampler.sample(kg.triples, generator=torch.Generator().manual_seed(0))
print(tuple(negatives.shape)) # (9, 4, 3)
assert signature_errors(negatives.reshape(-1, 3)) == []
# Trap in 1.5.1: entity_types alone does not restrict the sampler.
loose = TypedNegativeSampler(num_entities, num_negatives=20, entity_types=entity_types)
loose_negatives = loose.sample(kg.triples, generator=torch.Generator().manual_seed(0))
print(len(signature_errors(loose_negatives.reshape(-1, 3))) > 0) # True
Pass domains and ranges as sets or tensors of entity IDs. A relation without an entry falls back to all entities. The sampler also does not filter out known facts, so a "negative" can be a true triple; the next block drops those before training.
Multimodal entities and constrained ranking
Movies have a poster and a synopsis vector; users have a profile vector. Each modality is one tensor with a row for every entity, and a mask says which rows are real. The projectors are chosen by modality, not by entity type. The types enter through the masks, the sampler and the candidate mask at ranking time.
from tgraphx.kg import ImageEntityProjector, MultimodalKGModel, VectorEntityProjector
torch.manual_seed(0)
is_user, is_movie = entity_types == 0, entity_types == 1
profile = torch.zeros(num_entities, 5)
profile[is_user] = torch.randn(num_users, 5)
poster = torch.zeros(num_entities, 3, 32, 32)
poster[is_movie] = torch.rand(num_movies, 3, 32, 32)
synopsis = torch.zeros(num_entities, 24) # stands for precomputed text embeddings
synopsis[is_movie] = torch.randn(num_movies, 24)
features = {"profile": profile, "poster": poster, "synopsis": synopsis}
masks = {"profile": is_user, "poster": is_movie, "synopsis": is_movie}
model = MultimodalKGModel(num_entities, len(RELATIONS), out_dim=16, projectors={
"profile": VectorEntityProjector(5, 16),
"poster": ImageEntityProjector(3, 16), # averages over height and width
"synopsis": VectorEntityProjector(24, 16),
})
optimizer = torch.optim.Adam(model.parameters(), lr=0.05)
generator = torch.Generator().manual_seed(0)
known = set(map(tuple, kg.triples.tolist()))
for step in range(50):
negatives = sampler.sample(kg.triples, generator=generator).reshape(-1, 3)
negatives = negatives[torch.tensor([tuple(t) not in known for t in negatives.tolist()])]
embeddings = model.encode_entities(features, masks)
scores = torch.cat([model.score_triples(kg.triples, embeddings),
model.score_triples(negatives, embeddings)])
target = torch.cat([torch.ones(len(kg.triples)), torch.zeros(len(negatives))])
loss = nn.functional.binary_cross_entropy_with_logits(scores, target)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Which movie might user 1 rate next? Only entities in the relation's range are candidates.
user, rated = 1, RELATIONS.index("rated")
queries = torch.tensor([[user, rated, t] for t in range(num_entities)])
with torch.no_grad():
scores = model.score_triples(queries, model.encode_entities(features, masks))
allowed = torch.zeros(num_entities, dtype=torch.bool)
allowed[list(ranges[rated])] = True
allowed[[t for h, r, t in known if h == user and r == rated]] = False # already known
ranked = scores.masked_fill(~allowed, float("-inf")).argsort(descending=True)
ranked = ranked[:int(allowed.sum())]
assert len(ranked) == num_movies - 1
assert bool((entity_types[ranked] == ENTITY_TYPES["movie"]).all())
# Direction: score the sequel_of facts as stored, then with head and tail swapped.
sequels = kg.triples[kg.triples[:, 1] == SEQUEL]
with torch.no_grad():
embeddings = model.encode_entities(features, masks)
stored = model.score_triples(sequels, embeddings)
swapped = model.score_triples(sequels[:, [2, 1, 0]], embeddings)
print([round(s, 2) for s in stored.tolist()])
print([round(s, 2) for s in swapped.tolist()]) # the same numbers
assert torch.allclose(stored, swapped)
The features are random and the graph is tiny, so the ranking itself means nothing. What the code guarantees is structural: no user and no already-known movie can appear among the candidates, whatever the weights are.
ImageEntityProjector pools each image to one value per channel, so it discards spatial layout; encode images with a CNN first if layout matters. By default the model also adds a learned embedding for each entity, so a score cannot be attributed to the input modalities alone.
The decoder cannot learn direction. MultimodalKGModel scores with DistMult, which gives (h, r, t) and (t, r, h) the same score, as the last lines show. Training on (7, sequel_of, 6) therefore raises the score of (6, sequel_of, 7) just as much. Type signatures keep users and movies apart, but they cannot say which of two movies is the sequel. An asymmetric relation like this needs a different scorer: apply your own direction-aware function to the output of encode_entities, or use an ID-based model such as TransEModel or ComplExModel from tgraphx.kg, which does not take the feature projectors.
For a fuller treatment of the models and their evaluation, see knowledge graph embedding with tensor features.
When schema awareness pays for itself
The extra work is worth considering when:
- The schema is rich (many tables, fields and references).
- Data is limited, so structure you already know is worth encoding. Check this against a schema-free baseline.
- Explainability or constraint satisfaction is a requirement.
- A model must transfer across schemas, for example from one hospital's records to another's. This needs a design that takes the schema itself as input; the encoder above does not, because its layers are fixed to one schema.
It is usually not worth it when:
- The schema is flat (one table, no references).
- The dataset is large and a schema-free baseline already meets the target.
- There are no constraints to enforce and nothing to explain per field.
Honest limitations
Schema-aware architectures are an active research area, and there is no single best approach. TGraphX does not ship a schema language, signature or cardinality validation, or schema-conditioned generation. In 1.5.1, KnowledgeGraph is labelled beta, while the docstrings of TypedNegativeSampler, MultimodalKGModel and LogicalConstraintChecker label them Experimental. The code on this page is a pattern to adapt, not a framework.
Relation to TGraphX positioning
TGraphX positions itself around tensor-native graph learning and research-engineering tooling. Schema awareness is adjacent to that: the two share infrastructure (the KnowledgeGraph container, negative sampling, multimodal projectors) but address different problems.
If you are evaluating tools for schema-aware machine learning, start by asking which schema operations you need. Type-conditional embeddings, reference-aware aggregation, constraint checking and schema-constrained generation are different problems.
FAQ
Q: Is NeuroSchemaX shipped as a Python package?
A: Yes: neuroschemax is on PyPI. It is a separate project for visualizing and exporting neural network architecture diagrams, not a schema-aware encoder, and this article does not document it. TGraphX 1.5.1 contains no module by that name and does not depend on it.
Q: Can I use TGraphX's KG subsystem for schema-aware ML on non-KG data?
A: Indirectly, if you can reformulate your data as typed entities, relations and attributes. For relational tables that do not fit that mould, a different tool may be a better choice.
Q: How does this differ from heterogeneous GNNs?
A: Heterogeneous GNNs, built on containers such as HeteroData in PyG or HeteroGraph in TGraphX, handle node and edge types, which is one part of schema awareness. Ranges, cardinality rules and constrained outputs are not something a heterogeneous layer enforces for you. See heterogeneous graph learning.
Q: What about tabular deep learning?
A: It is a related field. Models such as TabNet and SAINT address tabular data without an explicit graph input, and schema-aware designs can borrow from them.