EasyTPP Models#
The public torch model classes are exported by easy_tpp.model:
- class easy_tpp.model.BaseModel(model_config)#
Bases:
Module- static generate_model_from_config(model_config)#
Generate the model in derived class based on model config.
- Parameters:
model_config (EasyTPP.ModelConfig) – config of model specs.
- static resolve_batch_inputs(batch=None, kwargs=None)#
Normalize model inputs.
Returns (time_seqs, time_delta_seqs, type_seqs, seq_non_pad_mask, attention_mask). Accepts HF-style keyword arguments; a dict or BatchEncoding; or the legacy positional tuple/list (deprecated).
- static get_logits_at_last_step(logits, batch_non_pad_mask, sample_len=None)#
Retrieve the hidden states of last non-pad events.
- Parameters:
logits (tensor) – [batch_size, seq_len, hidden_dim], a sequence of logits
batch_non_pad_mask (tensor) – [batch_size, seq_len], a sequence of masks
sample_len (tensor) – default None, use batch_non_pad_mask to find out the last non-mask position
ref: https://medium.com/analytics-vidhya/understanding-indexing-with-pytorch-gather-33717a84ebc4
- Returns:
retrieve the logits of EOS event
- Return type:
tensor
- compute_loglikelihood(time_delta_seq, lambda_at_event, lambdas_loss_samples, seq_mask, type_seq)#
Compute the loglikelihood of the event sequence based on Equation (8) of NHP paper.
- Parameters:
time_delta_seq (tensor) – [batch_size, seq_len], time_delta_seq from model input.
lambda_at_event (tensor) – [batch_size, seq_len, num_event_types], unmasked intensity at
event. ((right after) the)
lambdas_loss_samples (tensor) – [batch_size, seq_len, num_sample, num_event_types],
times. (intensity at sampling)
seq_mask (tensor) – [batch_size, seq_len], sequence mask vector to mask the padded events.
type_seq (tensor) – [batch_size, seq_len], sequence of mark ids, with padded events having a mark of self.pad_token_id
- Returns:
event loglike, non-event loglike, intensity at event with padding events masked
- Return type:
tuple
- integrate_samples(total_intensities, intervals)#
Integrate total intensity with the configured interval rule.
- compute_window_loss(batch=None, **kwargs)#
Positive final compensator, conditional on all real observed events.
Missing ends (including NaN entries in mixed batches) retain the last-event objective and emit one warning per model instance. Zero gaps bypass intensity evaluation and consume no additional MC draws.
- make_dtime_loss_samples(time_delta_seq)#
Generate the time point samples for every interval.
- Parameters:
time_delta_seq (tensor) – [batch_size, seq_len].
- Returns:
[batch_size, seq_len, n_samples]
- Return type:
tensor
- predict_one_step_at_every_event(batch=None, **kwargs)#
One-step prediction for every event in the sequence.
- Parameters:
batch (Mapping or tuple, optional) – Legacy batch input. Prefer passing time_seqs, time_delta_seqs, type_seqs, seq_non_pad_mask, and attention_mask as keyword inputs.
**kwargs – HF-style keyword model inputs.
- Returns:
- tensors of dtime and type prediction, [batch_size, seq_len].
Quadrature returns the window-truncated mean and the most probable type conditional on an event before the window end. With thinning.predict_median, a third tensor contains the window-truncated median; the mean remains the first output.
- Return type:
tuple
- predict_multi_step_since_last_event(batch=None, forward=False, **kwargs)#
Multi-step prediction since last event in the sequence.
- Parameters:
batch (Mapping or tuple, optional) – Legacy batch input. Prefer passing time_seqs, time_delta_seqs, type_seqs, seq_non_pad_mask, and attention_mask as keyword inputs.
forward (bool, optional) – Whether to use the entire sequence for prediction. Defaults to False.
**kwargs – HF-style keyword model inputs.
- Returns:
- predicted dtimes/types and label dtimes/types, each
[batch_size, num_step_gen], excluding the observed anchor.
- Return type:
tuple
- class easy_tpp.model.AttNHP(model_config)#
Bases:
BaseModelTorch implementation of Attentive Neural Hawkes Process, ICLR 2022. https://arxiv.org/abs/2201.00044. Source code: yangalan123/anhp-andtt
- compute_temporal_embedding(time)#
Compute the temporal embedding.
- Parameters:
time (tensor) – [batch_size, seq_len].
- Returns:
[batch_size, seq_len, emb_size].
- Return type:
tensor
- forward_pass(init_cur_layer, time_emb, sample_time_emb, event_emb, combined_mask)#
update the structure sequentially.
- Parameters:
init_cur_layer (tensor) – [batch_size, seq_len, hidden_size]
time_emb (tensor) – [batch_size, seq_len, hidden_size]
sample_time_emb (tensor) – [batch_size, seq_len, hidden_size]
event_emb (tensor) – [batch_size, seq_len, hidden_size]
combined_mask (tensor) – [batch_size, seq_len, hidden_size]
- Returns:
[batch_size, seq_len, hidden_size*2]
- Return type:
tensor
- seq_encoding(time_seqs, event_seqs)#
Encode the sequence.
- Parameters:
time_seqs (tensor) – time seqs input, [batch_size, seq_len].
event_seqs (_type_) – event type seqs input, [batch_size, seq_len].
- Returns:
event embedding, time embedding and type embedding.
- Return type:
tuple
- make_layer_mask(attention_mask)#
Create a tensor to do masking on layers.
- Parameters:
attention_mask (tensor) – mask for attention operation, [batch_size, seq_len, seq_len]
- Returns:
aim to keep the current layer, the same size of attention mask a diagonal matrix, [batch_size, seq_len, seq_len]
- Return type:
tensor
- make_combined_att_mask(attention_mask, layer_mask)#
Combined attention mask and layer mask.
- Parameters:
attention_mask (tensor) – mask for attention operation, [batch_size, seq_len, seq_len]
layer_mask (tensor) – mask for other layers, [batch_size, seq_len, seq_len]
- Returns:
[batch_size, seq_len * 2, seq_len * 2]
- Return type:
tensor
- forward(time_seqs, event_seqs, attention_mask, sample_times=None)#
Call the model.
- Parameters:
time_seqs (tensor) – [batch_size, seq_len], sequences of timestamps.
event_seqs (tensor) – [batch_size, seq_len], sequences of event types.
attention_mask (tensor) – [batch_size, seq_len, seq_len], masks for event sequences.
sample_times (tensor, optional) – [batch_size, seq_len, num_samples]. Defaults to None.
- Returns:
states at sampling times, [batch_size, seq_len, num_samples].
- Return type:
tensor
- loglike_loss(batch=None, **kwargs)#
Compute the loglike loss.
- Parameters:
batch (Mapping or tuple, optional) – Legacy batch input. Prefer HF-style keyword model inputs.
**kwargs – HF-style keyword model inputs.
- Returns:
loglike loss, num events.
- Return type:
list
- compute_states_at_sample_times(time_seqs, type_seqs, attention_mask, sample_times)#
Compute the states at sampling times.
- Parameters:
time_seqs (tensor) – [batch_size, seq_len], sequences of timestamps.
time_delta_seqs (tensor) – [batch_size, seq_len], sequences of delta times.
type_seqs (tensor) – [batch_size, seq_len], sequences of event types.
attention_mask (tensor) – [batch_size, seq_len, seq_len], masks for event sequences.
sample_dtimes (tensor) – delta times in sampling.
- Returns:
hiddens states at sampling times.
- Return type:
tensor
- compute_intensities_at_sample_times(time_seqs, time_delta_seqs, type_seqs, sample_dtimes, **kwargs)#
Compute the intensity at sampled times.
- Parameters:
time_seqs (tensor) – [batch_size, seq_len], sequences of timestamps.
time_delta_seqs (tensor) – [batch_size, seq_len], sequences of delta times.
type_seqs (tensor) – [batch_size, seq_len], sequences of event types.
sample_dtimes (tensor) – [batch_size, seq_len or 1, num_sample], offsets from history timestamps.
- Returns:
intensities as sampled_dtimes, [batch_size, seq_len, num_samples, event_num].
- Return type:
tensor
- class easy_tpp.model.FullyNN(model_config)#
Bases:
BaseModelTorch implementation of Fully Neural Network based Model for General Temporal Point Processes, NeurIPS 2019. https://arxiv.org/abs/1905.09690
- forward(time_seqs, time_delta_seqs, type_seqs)#
Call the model
- Parameters:
time_seqs (tensor) – [batch_size, seq_len], timestamp seqs.
time_delta_seqs (tensor) – [batch_size, seq_len], inter-event time seqs.
type_seqs (tensor) – [batch_size, seq_len], event type seqs.
- Returns:
hidden states at event times.
- Return type:
tensor
- loglike_loss(batch=None, **kwargs)#
Compute the loglike loss.
- Parameters:
batch (Mapping or tuple, optional) – Legacy batch input. Prefer HF-style keyword model inputs.
**kwargs – HF-style keyword model inputs.
- Returns:
loglike loss, num events.
- Return type:
list
- compute_intensities_at_sample_times(time_seqs, time_delta_seqs, type_seqs, sample_dtimes, **kwargs)#
Compute hidden states at sampled times.
- Parameters:
time_seqs (tensor) – [batch_size, seq_len], times seqs.
time_delta_seqs (tensor) – [batch_size, seq_len], time delta seqs.
type_seqs (tensor) – [batch_size, seq_len], event type seqs.
sample_dtimes (tensor) – [batch_size, seq_len, num_samples], sampled inter-event timestamps.
- Returns:
[batch_size, seq_len, num_samples, num_event_types], intensity at all sampled times.
- Return type:
tensor
- class easy_tpp.model.ITHP(model_config)#
Bases:
BaseModelInterpretable Transformer Hawkes Process, public-code architecture.
Paper: Meng et al., KDD 2024, https://arxiv.org/abs/2405.16059 Relevant pages: https://arxiv.org/pdf/2405.16059#page=3 (Sec. 4.1), https://arxiv.org/pdf/2405.16059#page=4 (Secs. 4.2-4.3), https://arxiv.org/pdf/2405.16059#page=5 (Secs. 4.4-4.5), and https://arxiv.org/pdf/2405.16059#page=9 (Sec. 5.4). Authors’ code, pinned at commit 5db1bb78f3323667e2cef478e177cd35971c4b43: waystogetthere/Interpretable-Transformer-Hawkes-Process
Paper-to-code decisions (line references are to the pinned source below):
Retained from paper Sec. 4.1/Eq. (3): concatenate sinusoidal time and learned type embeddings. Sec. 4.2/Eqs. (4)-(5): unprojected queries and keys with projected values. Public
Models.pylines 50-106 andSubLayers.pylines 194-236 implement these choices too.The paper’s Eqs. (4)-(5) have one attention matrix and do not specify a head-count hyperparameter. Public
Models.Encoderpassesn_headtoEncoderLayer, but the activedynamic_v_attentionnever uses it; the separateMultiHeadAttentionclass is inactive. See publicModels.pylines 50-68,Layers.pylines 9-23, andSubLayers.pylines 13-69 and 194-236.Main.pyline 258 defaults to one head. We therefore have one attention map and ignore EasyTPP’s genericnum_headssetting (whose default is 2).Paper Eq. (5) scales the 2M-wide query/key dot product by sqrt(2M). Public
dynamic_v_attentioninstead divides by sqrt(d_k) (SubLayers.pyline 222). We follow the executed public rule.Paper Eq. (7) writes a type-specific softplus head directly on the attention-weighted value sum. However, paper Sec. 5.4 explicitly says the encoder keeps a skip connection and requires M_V=2M; Eq. (7) does not show how that connection enters the intensity. Public code resolves this ambiguity with a projection, query residual, layer norm, and GELU feed-forward block before the type-specific decoder (
SubLayers.pylines 194-301;Layers.pylines 9-23;Models.pylines 203-236). We use that executed path, including its forced single encoder layer (Models.pylines 65-68), rather than silently inventing an Eq. (7) variant. Its intensity does not have Eq. (7)’s exact additive form.Paper Sec. 4.4/Eq. (7) defines a marked intensity at event and non-event times using only preceding events as keys. Public
Models.Transformer.forwardloops over candidate types (lines 203-236) and excludes grid points as keys (Models.pylines 83-96). We vectorize the same candidate-type computation, using EasyTPP’s zero-based marks instead of the public code’s one-based marks.Paper Sec. 4.5/Eq. (8) scores events from the beginning of each sequence and integrates on [0,T] using an unspecified sufficiently fine grid. Public
Utils.gen_Xne(lines 104-142) instead makes a batch-wide 0.1 grid and shifts time by the batch minimum;Main.pylines 62-72 passes it toModels.Transformer.forward. We condition on the first observed event, as EasyTPP baselines do, and integrate each sequence’s observed intervals separately to remove dependence on unrelated batch members. No batch-wide time shift is applied.For that integral,
integration_method='mc'draws independent uniform times per interval by default;'trapezoid'uses evenly spaced nodes and'fixed_grid'uses per-interval midpoint cells. This replaces the authors’ active batch-wide 0.1 grid with a per-interval approximation independent of other batch members. The separate public MC helper (Utils.pylines 42-59) is not called by the activeMain.pypath. Our reported runs used 20 draws per interval for training/validation and 100 for test likelihood; sample counts are an approximation choice, not a number specified by paper Sec. 4.5. Evenfixed_gridwithgrid_step=0.1is a per-interval midpoint rule, not a reproduction of the public batch-wide grid.Paper Eq. (8) describes maximum likelihood alone. Public
Main.pylines 62-115 adds 0.5 times next-type cross entropy in training. We retain that public training term but report pure point-process NLL on validation/test. PublicMain.pylines 32-47 and 177-208 select a checkpoint using test LL; EasyTPP instead selects by validation LL, keeping the test split held out.Paper Eqs. (5) and (7) require strictly preceding events. Public
Models.get_subsequent_mask(lines 28-36) masks the entire first row, thendynamic_v_attentionsoftmaxes its finite mask values (SubLayers.pylines 222-227). We zero empty-history attention and do not score the first event, avoiding future leakage at that row.
Select the integration rule through
model_specs.integration_method; EasyTPP serializes that field but omitsuse_mc_samplesandnum_heads.Our reported runs used Adam epsilon 1e-5 and gradient-norm clipping at 1. EasyTPP’s standard runner does not apply those settings, so fresh training here does not exactly reproduce that training path.
Pinned code for the line references above: waystogetthere/Interpretable-Transformer-Hawkes-Process waystogetthere/Interpretable-Transformer-Hawkes-Process waystogetthere/Interpretable-Transformer-Hawkes-Process waystogetthere/Interpretable-Transformer-Hawkes-Process waystogetthere/Interpretable-Transformer-Hawkes-Process
- make_dtime_loss_samples(time_delta_seq)#
Draw random MC times or fixed trapezoid nodes per interval.
Upstream EasyTPP’s BaseModel currently returns
linspacefor both modes; overriding it implements the selected integration method.
- compute_temporal_embedding(times)#
Encode absolute timestamps with the released sinusoidal features.
- forward(time_seqs, type_seqs, batch_non_pad_mask)#
Compute marked intensities for events after the first event.
- compute_intensities_at_sample_times(time_seqs, time_delta_seqs, type_seqs, sample_dtimes, **kwargs)#
Compute marked intensities after each supplied source event.
- loglike_loss(batch=None, **kwargs)#
Compute ITHP likelihood and optional auxiliary type loss.
- class easy_tpp.model.IntensityFree(model_config)#
Bases:
BaseModelTorch implementation of Intensity-Free Learning of Temporal Point Processes, ICLR 2020. https://openreview.net/pdf?id=HygOjhEYDH
reference: shchur/ifl-tpp
- forward(time_delta_seqs, type_seqs)#
Call the model.
- Parameters:
time_delta_seqs (tensor) – [batch_size, seq_len], inter-event time seqs.
type_seqs (tensor) – [batch_size, seq_len], event type seqs.
- Returns:
hidden states, [batch_size, seq_len, hidden_dim], states right before the event happens.
- Return type:
list
- loglike_loss(batch=None, **kwargs)#
Compute the loglike loss.
- Parameters:
batch (Mapping or tuple, optional) – Legacy batch input. Prefer HF-style keyword model inputs.
**kwargs – HF-style keyword model inputs.
- Returns:
loglikelihood loss and num of events.
- Return type:
tuple
- compute_intensities_at_sample_times(time_seqs, time_delta_seqs, type_seqs, sample_dtimes, **kwargs)#
Compute marked intensities at sampled inter-event times.
- Parameters:
time_seqs (tensor) – [batch_size, seq_len], event timestamps.
time_delta_seqs (tensor) – [batch_size, seq_len], inter-event times.
type_seqs (tensor) – [batch_size, seq_len], event types.
sample_dtimes (tensor) – [batch_size, seq_len, num_samples], sampled inter-event times.
- Returns:
[batch_size, seq_len, num_samples, num_event_types], marked intensities.
- Return type:
tensor
- predict_one_step_at_every_event(batch=None, **kwargs)#
One-step prediction for every event in the sequence.
- Parameters:
batch (Mapping or tuple, optional) – Legacy batch input. Prefer passing model inputs as keywords.
**kwargs – HF-style keyword model inputs.
- Returns:
tensors of dtime and type prediction, [batch_size, seq_len].
- Return type:
tuple
- class easy_tpp.model.NHP(model_config)#
Bases:
BaseModelTorch implementation of The Neural Hawkes Process: A Neurally Self-Modulating Multivariate Point Process, NeurIPS 2017, https://arxiv.org/abs/1612.09328.
- forward(batch)#
Suppose we have inputs with original sequence length N+1 ts: [t0, t1, …, t_N] dts: [0, t1 - t0, t2 - t1, …, t_N - t_{N-1}] marks: [k0, k1, …, k_N] (k0 and kN could be padded marks if t0 and tN correspond to left and right windows)
- Returns:
(batch_size, seq_len - 1, hidden_dim) Right limits of [t_0, …, t_{N-1}, t_N] of shape: (batch_size, seq_len, 4 * hidden_dim) We need the right limit of t_N to sample continuation.
- Return type:
Left limits of [t_1, …, t_N] of shape
> rnn_cell.recurrence(event_emb_t, h_tm1, c_tm1, c_bar_tm1) -> c_t, c_bar_t, gate_delta, gate_o > rnn_cell.decay(c_t, c_bar_t, delta_t, o_t, dt) -> c_d_t, h_d_t
- get_states(right_hiddens, sample_dts)#
right_hiddens: (batch_size, seq_len, 4 * hidden_dim): (c_t, c_bar_t, delta_t, o_t) sample_dts: (batch_size, seq_len, MC_points)
> rnn_cell.decay(c_t, c_bar_t, delta_t, o_t, dt) -> c_d_t, h_d_t
- loglike_loss(batch=None, **kwargs)#
Compute the log-likelihood loss.
- Parameters:
batch (Mapping or tuple, optional) – Legacy batch input. Prefer HF-style keyword model inputs.
**kwargs – HF-style keyword model inputs.
- Returns:
loglikelihood loss and num of events.
- Return type:
tuple
- compute_intensities_at_sample_times(time_seqs, time_delta_seqs, type_seqs, sample_dtimes, **kwargs)#
Compute the intensity at sampled times, not only event times.
- Parameters:
time_seqs (tensor) – [batch_size, seq_len], times seqs.
time_delta_seqs (tensor) – [batch_size, seq_len], time delta seqs.
type_seqs (tensor) – [batch_size, seq_len], event type seqs.
sample_dtimes (tensor) – [batch_size, seq_len, num_sample], sampled inter-event timestamps.
- Returns:
- [batch_size, num_times, num_mc_sample, num_event_types],
intensity at each timestamp for each event type.
- Return type:
tensor
- class easy_tpp.model.ODETPP(model_config)#
Bases:
BaseModelTorch implementation of a TPP with Neural ODE state evolution, which is a simplified version of TPP in https://arxiv.org/abs/2011.04583, ICLR 2021
code reference: https://msurtsukov.github.io/Neural-ODE/; liruilong940607/NeuralODE
- forward(time_delta_seqs, type_seqs)#
Call the model.
- Parameters:
time_delta_seqs (tensor) – [batch_size, seq_len], inter-event time seqs.
type_seqs (tensor) – [batch_size, seq_len], event type seqs.
- Returns:
hidden states at event times.
- Return type:
tensor
- loglike_loss(batch=None, **kwargs)#
Compute the loglike loss.
- Parameters:
batch (Mapping or tuple, optional) – Legacy batch input. Prefer HF-style keyword model inputs.
**kwargs – HF-style keyword model inputs.
- Returns:
loglike loss, num events.
- Return type:
list
- compute_states_at_sample_times(state_ti_plus, sample_dtimes)#
Compute the states at sampling times.
- Parameters:
state_ti_plus (tensor) – [batch_size, seq_len, hidden_size], states right after the events.
sample_dtimes (tensor) – [batch_size, seq_len, num_samples], delta times in sampling.
- Returns:
hiddens states at sampling times.
- Return type:
tensor
- compute_intensities_at_sample_times(time_seqs, time_delta_seqs, type_seqs, sample_dtimes, **kwargs)#
Compute the intensity at sampled times, not only event times.
- Parameters:
time_seqs (tensor) – [batch_size, seq_len], times seqs.
time_delta_seqs (tensor) – [batch_size, seq_len], time delta seqs.
type_seqs (tensor) – [batch_size, seq_len], event type seqs.
sample_dtimes (tensor) – [batch_size, seq_len, num_sample], sampled inter-event timestamps.
- Returns:
- [batch_size, num_times, num_mc_sample, num_event_types],
intensity at each timestamp for each event type.
- Return type:
tensor
- class easy_tpp.model.RMTPP(model_config)#
Bases:
BaseModelTorch implementation of Recurrent Marked Temporal Point Processes, KDD 2016. https://www.kdd.org/kdd2016/papers/files/rpp1081-duA.pdf
- evolve_and_get_intentsity(right_hiddens_BNH, dts_BNG)#
Eq.11 that computes intensity.
- forward(batch)#
Suppose we have inputs with original sequence length N+1 ts: [t0, t1, …, t_N] dts: [0, t1 - t0, t2 - t1, …, t_N - t_{N-1}] marks: [k0, k1, …, k_N] (k0 and kN could be padded marks if t0 and tN correspond to left and right windows)
- Returns:
(batch_size, seq_len - 1, hidden_dim) right limits of hidden states [t_0, …, t_{N-1}, t_N] of shape: (batch_size, seq_len, hidden_dim) We need the right limit of t_N to sample continuation.
- Return type:
left limits of intensity at [t_1, …, t_N] of shape
- loglike_loss(batch=None, **kwargs)#
Compute the log-likelihood loss.
- Parameters:
batch (Mapping or tuple, optional) – Legacy batch input. Prefer HF-style keyword model inputs.
**kwargs – HF-style keyword model inputs.
- Returns:
loglikelihood loss and num of events.
- Return type:
tuple
- compute_intensities_at_sample_times(time_seqs, time_delta_seqs, type_seqs, sample_dtimes, **kwargs)#
Compute the intensity at sampled times, not only event times.
- Parameters:
time_seq (tensor) – [batch_size, seq_len], times seqs.
time_delta_seq (tensor) – [batch_size, seq_len], time delta seqs.
event_seq (tensor) – [batch_size, seq_len], event type seqs.
sample_dtimes (tensor) – [batch_size, seq_len, num_sample], sampled inter-event timestamps.
- Returns:
- [batch_size, num_times, num_mc_sample, num_event_types],
intensity at each timestamp for each event type.
- Return type:
tensor
- class easy_tpp.model.S2P2(model_config)#
Bases:
BaseModel- forward(batch, initial_state_BLP: Tensor | None = None, **kwargs) Tuple[Tensor, Tensor]#
Batch operations of self._forward
- compute_intensities_at_sample_times(event_times_BN, inter_event_times_BN, marks_BN, sample_dtimes, **kwargs)#
Compute the intensity at sampled times, not only event times. from the left limit
- Parameters:
time_seq (tensor) – [batch_size, seq_len], times seqs.
time_delta_seq (tensor) – [batch_size, seq_len], time delta seqs.
event_seq (tensor) – [batch_size, seq_len], event type seqs.
sample_dtimes (tensor) – [batch_size, seq_len, num_sample], sampled inter-event timestamps.
- Returns:
- [batch_size, num_times, num_mc_sample, num_event_types],
intensity at each timestamp for each event type.
- Return type:
tensor
- class easy_tpp.model.SAHP(model_config)#
Bases:
BaseModelTorch implementation of Self-Attentive Hawkes Process, ICML 2020. Part of the code is collected from yangalan123/anhp-andtt
I slightly modify the original code because it is not stable.
- state_decay(encode_state, duration_t)#
Equation (15), which computes the pre-intensity states
- Parameters:
encode_state (tensor) – [batch_size, seq_len, hidden_size].
duration_t (tensor) – [batch_size, seq_len, num_sample].
- Returns:
hidden states at event times.
- Return type:
tensor
- forward(time_seqs, time_delta_seqs, event_seqs, attention_mask)#
Call the model
- Parameters:
time_seqs (tensor) – [batch_size, seq_len], timestamp seqs.
time_delta_seqs (tensor) – [batch_size, seq_len], inter-event time seqs.
event_seqs (tensor) – [batch_size, seq_len], event type seqs.
attention_mask (tensor) – [batch_size, seq_len, hidden_size], attention masks.
- Returns:
hidden states at event times.
- Return type:
tensor
- loglike_loss(batch=None, **kwargs)#
Compute the log-likelihood loss.
- Parameters:
batch (Mapping or tuple, optional) – Legacy batch input. Prefer HF-style keyword model inputs.
**kwargs – HF-style keyword model inputs.
- Returns:
loglike loss, num events.
- Return type:
list
- compute_states_at_sample_times(encode_state, sample_dtimes)#
Compute the hidden states at sampled times.
- Parameters:
encode_state (tensor) – three tensors with each shape [batch_size, seq_len, hidden_size].
sample_dtimes (tensor) – [batch_size, seq_len, num_samples].
- Returns:
[batch_size, seq_len, num_samples, hidden_size], hidden state at each sampled time.
- Return type:
tensor
- compute_intensities_at_sample_times(time_seqs, time_delta_seqs, type_seqs, sample_dtimes, **kwargs)#
Compute hidden states at sampled times.
- Parameters:
time_seqs (tensor) – [batch_size, seq_len], times seqs.
time_delta_seqs (tensor) – [batch_size, seq_len], time delta seqs.
type_seqs (tensor) – [batch_size, seq_len], event type seqs.
sample_dtimes (tensor) – [batch_size, seq_len, num_samples], sampled inter-event timestamps.
- Returns:
[batch_size, seq_len, num_samples, num_event_types], intensity at all sampled times.
- Return type:
tensor
- class easy_tpp.model.THP(model_config)#
Bases:
BaseModelTorch implementation of Transformer Hawkes Process, ICML 2020, https://arxiv.org/abs/2002.09291. Note: Part of the code is collected from yangalan123/anhp-andtt.
- forward(time_seqs, type_seqs, attention_mask)#
Call the model
- Parameters:
time_seqs (tensor) – [batch_size, seq_len], timestamp seqs.
type_seqs (tensor) – [batch_size, seq_len], event type seqs.
attention_mask (tensor) – [batch_size, seq_len, hidden_size], attention masks.
- Returns:
hidden states at event times.
- Return type:
tensor
- loglike_loss(batch=None, **kwargs)#
Compute the loglike loss.
- Parameters:
batch (Mapping or tuple, optional) – Legacy batch input. Prefer HF-style keyword model inputs.
**kwargs – HF-style keyword model inputs.
- Returns:
loglike loss, num events.
- Return type:
tuple
- compute_states_at_sample_times(event_states, sample_dtimes)#
Compute the hidden states at sampled times.
- Parameters:
event_states (tensor) – [batch_size, seq_len, hidden_size].
sample_dtimes (tensor) – [batch_size, seq_len, num_samples].
- Returns:
hidden state at each sampled time.
- Return type:
tensor
- compute_intensities_at_sample_times(time_seqs, time_delta_seqs, type_seqs, sample_dtimes, **kwargs)#
Compute hidden states at sampled times.
- Parameters:
time_seqs (tensor) – [batch_size, seq_len], times seqs.
time_delta_seqs (tensor) – [batch_size, seq_len], time delta seqs.
type_seqs (tensor) – [batch_size, seq_len], event type seqs.
sample_dtimes (tensor) – [batch_size, seq_len, num_samples], sampled inter-event timestamps.
- Returns:
[batch_size, seq_len, num_samples, num_event_types], intensity at all sampled times.
- Return type:
tensor
- class easy_tpp.model.WSMTHP(model_config)#
Bases:
BaseModelTHP encoder trained with Weighted Score Matching (WSM).
The class name
WSMTHPmust match themodel_idfield in the YAML config.YAML
model_configparameters#Standard (top-level):
hidden_size int Transformer embedding / model dimension. num_layers int Number of Transformer encoder layers. num_heads int Number of attention heads. dropout_rate float Dropout probability.
WSM-specific (under
model_specs):d_inner int FFN inner dimension (default: hidden_size * 2). CE_coef float Weight for the mark cross-entropy term (default: 10.0). h_type str Weight function selector; currently only ``'two_side_op'`` is supported (default). T_mode str How to obtain the observation window end T: ``'manual'``, ``'train_global'``, or ``'batch'``. max_observed_time float Observation window end T used when ``T_mode`` is ``'manual'``. When omitted under ``'batch'``, T = max(time_seqs) inside each batch.- forward(batch)#
Run the encoder on a batch.
- Parameters:
batch – tuple (time_seqs, time_delta_seqs, type_seqs, non_pad_mask, attn_mask)
- Returns:
[B, N, d_model]
- Return type:
enc_output
- nll_loss(batch, **kwargs)#
Compute approximate negative log-likelihood for evaluation.
- loglike_loss(batch=None, **kwargs)#
Compute the WSM training loss.
Required by EasyTPP’s ModelWrapper.run_batch(). Despite the method name, this returns the Weighted Score Matching objective (NOT log-likelihood). See module docstring for details.
- Parameters:
batch – Legacy mapping or positional batch. Prefer HF-style keyword model inputs.
**kwargs – HF-style keyword model inputs.
- Returns:
scalar Tensor (WSM + CE mark loss) num_events: int, number of real (non-padded) events in the batch
- Return type:
loss
- compute_intensities_at_sample_times(time_seqs, time_delta_seqs, type_seqs, sample_dtimes, **kwargs)#
Compute intensities at sampled inter-event times (for thinning-based generation).
Called by the EventSampler in BaseModel for prediction.
- Parameters:
time_seqs – [B, N]
time_delta_seqs – [B, N]
type_seqs – [B, N]
sample_dtimes – [B, N, S]
- Returns:
[B, N, S, M] or [B, 1, S, M] intensities
- class easy_tpp.model.EventSampler(num_sample, num_exp, over_sample_rate, num_samples_boundary, dtime_max, patience_counter, device, max_iterations=10000, bound_grid='log')#
Bases:
ModuleEvent Sequence Sampler based on thinning algorithm, which corresponds to Algorithm 2 of The Neural Hawkes Process: A Neurally Self-Modulating Multivariate Point Process, https://arxiv.org/abs/1612.09328.
The implementation uses code from yangalan123/anhp-andtt.
- compute_bound_grid(boundary, num_grid_points=None, *, dtype=None)#
Return explicit [batch, seq, G] segment edges over each window.
- compute_intensity_upper_bound(time_seq, time_delta_seq, event_seq, intensity_fn, compute_last_step_only, dtime_boundary=None)#
Compute the maximum segment bound at each event timestamp.
- Parameters:
time_seq (tensor) – [batch_size, seq_len], timestamp seqs.
time_delta_seq (tensor) – [batch_size, seq_len], time delta seqs.
event_seq (tensor) – [batch_size, seq_len], event type seqs.
intensity_fn (fn) – a function that computes the intensity.
compute_last_step_only (bool) – whether to compute the last time step only.
dtime_boundary (tensor) – future window end; defaults to dtime_max.
- Returns:
[batch_size, seq_len]
- Return type:
tensor
- compute_intensity_segment_bounds(time_seq, time_delta_seq, event_seq, intensity_fn, compute_last_step_only, dtime_boundary=None)#
Return [batch, seq, G-1] local bounds from G bound-grid points.
G is max(num_samples_boundary, MIN_BOUND_GRID_POINTS). Each segment uses the larger total intensity at its two endpoints, multiplied by over_sample_rate. Sampling is exact when these bounds dominate the intensity throughout each segment. For general neural intensities the grid-derived bounds are an approximation: a narrow peak between grid points can be missed. Raise num_samples_boundary and/or over_sample_rate to improve coverage. Observed violations trigger retries of the affected interval, but cannot detect unobserved peaks.
- sample_exp_distribution(sample_rate)#
Sample an exponential distribution.
- Parameters:
sample_rate (tensor) – [batch_size, seq_len], or per-stream [batch_size, seq_len, num_sample], intensity rate.
- Returns:
- [batch_size, seq_len, num_sample, num_exp], independent
exponential proposal streams for each requested draw.
- Return type:
tensor
- sample_uniform_distribution(intensity_upper_bound)#
Sample an uniform distribution
- Parameters:
intensity_upper_bound (tensor) – upper bound intensity computed in the previous step.
- Returns:
[batch_size, seq_len, num_sample, num_exp]
- Return type:
tensor
- sample_accept(unif_numbers, sample_rate, total_intensities, exp_numbers, dtime_boundary=None)#
Do the sample-accept process.
For the accumulated exp (delta) samples drawn for each event timestamp, find (from left to right) the first that makes the criterion < 1 and accept it as the sampled next-event time. If all exp samples are rejected (criterion >= 1), then we use the window boundary (default dtime_max).
- Parameters:
unif_numbers (tensor) – [batch_size, max_len, num_sample, num_exp], sampled uniform random number.
sample_rate (tensor) – [batch_size, max_len], or per-stream [batch_size, max_len, num_sample], or per-proposal [batch_size, max_len, num_sample, num_exp], sample rate (intensity).
total_intensities (tensor) – [batch_size, seq_len, num_sample, num_exp]
exp_numbers (tensor) – [batch_size, seq_len, num_sample, num_exp]: sampled exp numbers (delta in Algorithm 2).
dtime_boundary (tensor) – [batch_size, seq_len], optional window end.
- Returns:
[batch_size, seq_len, num_sample], sampled next-event times.
- Return type:
result (tensor)
- draw_next_time_one_step(time_seq, time_delta_seq, event_seq, dtime_boundary, intensity_fn, compute_last_step_only=False)#
Sample independent next-event times with piecewise-constant thinning.
Thinning with a piecewise-constant dominating rate follows Lewis & Shedler (1979) / Ogata (1981). Proposals and the bound grid use [0, dtime_boundary]. Samples without an event in this finite window are censored at its boundary. Each chunk draws Exp(1) increments in cumulative-bound space and inverts the piecewise-linear integral, allowing proposals to cross any number of segments in one pass. num_exp controls the proposal chunk size, not the number of attempts. If an in-window proposal exceeds the bound, restart that interval with an increased bound, at most patience_counter times; then raise rather than silently return samples from an invalid envelope.
The grid has max(num_samples_boundary, MIN_BOUND_GRID_POINTS) points (at least 21); each segment’s larger endpoint total intensity is multiplied by over_sample_rate. Sampling is exact when these bounds dominate the intensity. For general neural intensities they are an approximation: a narrow peak between grid points can be missed, even with violation retries. Raise num_samples_boundary and/or over_sample_rate to improve coverage. After max_iterations proposal passes per call, unfinished sampling raises RuntimeError.
- Parameters:
time_seq (tensor) – [batch_size, seq_len], timestamp seqs.
time_delta_seq (tensor) – [batch_size, seq_len], time delta seqs.
event_seq (tensor) – [batch_size, seq_len], event type seqs.
dtime_boundary (tensor) – [batch_size, seq_len], dtime upper bound.
intensity_fn (fn) – a function to compute the intensity.
compute_last_step_only (bool, optional) – whether to compute last event timestep only. Defaults to False.
- Returns:
next event time prediction and weight.
- Return type:
tuple