Text Generation
Transformers
Safetensors
English
modernbert
fill-mask
sentiment-control
continuous-control
controllable-text-generation
encoder-generation
non-autoregressive
masked-language-model
text-style-transfer
data-augmentation
emnlp2026
Run this model with HF Jobs
Run shawhed/SenseShift-large on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/shawhed/SenseShift-large. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/shawhed/SenseShift-large on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/shawhed/SenseShift-large. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/shawhed/SenseShift-large. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use shawhed/SenseShift-large with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use shawhed/SenseShift-large with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="shawhed/SenseShift-large")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForMaskedLM tokenizer = AutoTokenizer.from_pretrained("shawhed/SenseShift-large") model = AutoModelForMaskedLM.from_pretrained("shawhed/SenseShift-large", device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use shawhed/SenseShift-large with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "shawhed/SenseShift-large" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "shawhed/SenseShift-large", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/shawhed/SenseShift-large
- SGLang
How to use shawhed/SenseShift-large with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "shawhed/SenseShift-large" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "shawhed/SenseShift-large", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "shawhed/SenseShift-large" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "shawhed/SenseShift-large", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use shawhed/SenseShift-large with Docker Model Runner:
docker model run hf.co/shawhed/SenseShift-large
Focused model card; explicit generation parameters
Browse filesFiles changed (7)
- README.md+113-151
- senseshift/__pycache__/__init__.cpython-311.pycAdded
- senseshift/__pycache__/decoding.cpython-311.pycAdded
- senseshift/__pycache__/masking.cpython-311.pycAdded
- senseshift/__pycache__/pipeline.cpython-311.pycAdded
- senseshift/__pycache__/text_utils.cpython-311.pycAdded
- senseshift/pipeline.py+38-7
11 unmodified lines12131415161718192 unmodified lines222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707 unmodified lines7879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021111 unmodified lines- non-autoregressive- masked-language-model- text-style-transfer- sentiment-transfer- text-rewriting- modernbert- emnlp2026language:2 unmodified lines# SenseShift-large> **Generation from an encoder, with continuous control.**> An accepted EMNLP 2026 paper. Not a classifier, not a decoder — a masked LM> that *writes* text at a sentiment you dial in.SenseShift rewrites a sentence — or writes a new one — at **any sentiment you askfor on a continuous −1.0 to +1.0 scale**, while keeping it consistent with thesurrounding text.Two things make it unusual:- **Continuous, not categorical.** Most sentiment-controlled generation offersyou `positive` / `negative` / `neutral`. SenseShift takes a *number* — 21points on a 0.1 grid. Sweeping one sentence of a story, everything else fixed:| target | achieved | rewritten sentence || ---: | ---: | --- || −0.9 | −0.7 | The water was bitter and made him sick. || −0.6 | −0.4 | The water was bitter and made him cough. || +0.0 | +0.0 | The water was cold and made him wet. || +0.6 | +0.7 | The water was clear and tasted very good. || +0.9 | +0.8 | His friends laughed and played games with him. |- **The generator is an encoder.** Text generation is nearly alwaysautoregressive decoding. SenseShift generates by iteratively filling maskedpositions in a bidirectional ModernBERT, so every token it writes isconditioned on the text on *both* sides. That is what lets it drop areplacement sentence into the middle of a passage and have it fit.It is a masked language model fine-tuned from ModernBERT-large with an explicit**control vocabulary**: 21 special tokens `[-1.0] … [1.0]` on a 0.1 grid. Attraining time every sentence is prefixed with its own VADER sentiment token andone sentence is masked out, so the model learns to write a replacement thatrealises the requested sentiment in context.| Model | Base | Params || --- | --- | --- || [SenseShift-base](https://huggingface.co/shawhed/SenseShift-base) | ModernBERT-base | 150M || **SenseShift-large** (this model) | ModernBERT-large | 396M |## UsageNo install needed — the inference code ships inside this repo. Clone it and youhave the weights and the code together:```bashgit clone https://huggingface.co/shawhed/SenseShift-large7 unmodified linesshifter = SenseShift.from_pretrained("SenseShift-large")text = ("The waiter greeted us at the door. ""The food arrived quickly and was still hot. ""We paid the bill and walked back to the hotel.")# Rewrite sentence 1 as strongly negativeout = shifter.generate(text, generation_mode="rewrite", sentence_index=1, sentiment=-0.9)print(out.sentence) # -> "He looked sad and we felt bad."print(out.text) # the full passage with that sentence swapped in# Add a positive sentence after the last oneout = shifter.generate(text, generation_mode="add", sentiment=0.7)print(out.text)```Or let `huggingface_hub` fetch it into the local cache instead of cloning:```pythonimport sysfrom huggingface_hub import snapshot_downloadpath = snapshot_download("shawhed/SenseShift-large")sys.path.insert(0, path)from senseshift import SenseShiftshifter = SenseShift.from_pretrained(path)```Requirements: `torch`, `transformers`, `huggingface-hub`, `nltk` (see`requirements.txt`). The VADER lexicon downloads itself on first use.### `generate` arguments| Argument | Meaning || --- | --- || `text` | The passage to edit. || `generation_mode` | `"rewrite"` replaces the sentence at `sentence_index`; `"add"` inserts a new sentence right after it. || `sentiment` | `None` → keep the sentiment already there. `"random"` → a random grid value, excluding the current one. A number in `[-1, 1]` → that value, snapped to the nearest 0.1. || `sentence_index` | Which sentence to act on. Defaults to a random sentence (`rewrite`) or the last sentence (`add`). Negative indices count from the end. || `num_masks` | How many mask slots the model gets, i.e. roughly how long the new sentence is. Defaults to the replaced sentence's word count (`rewrite`) or `12` (`add`). || `seed` | Seeds the random index / sentiment draws. |Decoding can be tuned per call: `top_k`, `beam_size`, `max_iters`, `alpha`(length normalisation), `gamma` (beam diversity penalty), `temperature`,`min_words`.`generate` returns a `SenseShiftOutput` with `.text`, `.sentence`,`.target_sentiment`, `.achieved_sentiment` (VADER of what was actually written),`.beams`, and friends. `str(out)` gives the edited passage.## How it works1. Split the passage into sentences and score each with VADER.2. Prefix every sentence with its control token; give the target sentence the*requested* token and replace its words with `[MASK]`s.3. Fill the masks left to right with beam search over the MLM head, with lengthnormalisation and a diversity penalty, stopping at terminal punctuation.4. Splice the decoded sentence back into the passage.Steps 1–4 live in the `senseshift` package, not in the weights — the checkpointitself is a stock `ModernBertForMaskedLM` and can be loaded with`AutoModelForMaskedLM` if you want to build your own decoding loop.## Control fidelity, and how far it transfersMeasured over 50 held-out passages per domain, 9 targets each, rewriting onerandomly chosen sentence. "Achieved" is VADER on the sentence the model wrote.| target | achieved — stories *(in-domain)* | achieved — reviews *(out-of-domain)* || ---: | ---: | ---: || −0.9 | −0.40 | −0.44 || −0.6 | −0.23 | −0.25 || −0.3 | −0.14 | −0.04 || +0.0 | +0.09 | +0.01 || +0.3 | +0.22 | +0.14 || +0.6 | +0.53 | +0.47 || +0.9 | +0.75 | +0.73 || **MAE** | **0.33** | **0.33** |Two things to read off this.**The response is monotone and the positive half is well calibrated** — targetsof +0.6 and +0.9 land within about 0.15. The negative half is compressed: askfor −0.9 and you reliably get *more negative*, but around −0.4 rather than −0.9.**Domain transfer is essentially free.** SenseShift-large was trained only onshort children's stories, yet product reviews — a domain it never saw, withdifferent vocabulary, register and length — come out at an identical MAE of0.33. The per-target curve is the same shape. Use it outside the story domainwith reasonable confidence.## Training data and usable rangeTrained on TinyStories-style children's stories, labelled per sentence withVADER. That corpus is lopsided, which directly shapes what the model can do:| sentiment of training sentences | share || --- | ---: || negative (< 0) | 15.3% || neutral (= 0) | 37.8% || positive (> 0) | 47.0% || exactly −1.0 | **0.00%** || exactly +1.0 | 0.10% |So:- **Use targets in −0.8 … +0.9.** The `[-1.0]` control token appears *zero*times in training and `[1.0]` almost never; asking for ±1.0 gives anundertrained token and unpredictable output. `-1.0` in particular comes backnear-neutral.- **Negative control is looser than positive**, because negative sentences area third as common in the corpus. For strongly negative text, ask for −0.9 andexpect roughly −0.4, or resample.## Limitations- English only; trained on short children's stories, though it transfers toother domains at no measured cost (see above).- VADER supplies the sentiment labels, so the model inherits its lexicon-basedview of sentiment.- Control is a steer, not a guarantee: MAE 0.33 over the grid, with the negativehalf compressed and `±1.0` unusable. Single generations are noisy — check`out.achieved_sentiment` and resample if you need a specific value.- The rewrite is length-bounded by `num_masks`, so very long sentences areusually replaced by something shorter.- Because the whole passage is re-encoded per mask fill, generation cost growswith `num_masks × beam_size`.## CitationAccepted to **EMNLP 2026**. A preprint and the full BibTeX entry will be linkedhere once they are public.11 unmodified lines121314151617182 unmodified lines212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798997 unmodified lines10710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217311 unmodified lines- non-autoregressive- masked-language-model- text-style-transfer- data-augmentation- modernbert- emnlp2026language:2 unmodified lines# SenseShift-largeRewrite any sentence in a passage — or write a new one — at a sentiment youchoose on a continuous scale from **−1.0 to +1.0**, in context.| Model | Base | Params || --- | --- | --- || [SenseShift-base](https://huggingface.co/shawhed/SenseShift-base) | ModernBERT-base | 150M || **SenseShift-large** (this model) | ModernBERT-large | 396M |Accepted to EMNLP 2026.## How it worksSentiment is a **control vocabulary**: 21 special tokens `[-1.0] … [1.0]` on a0.1 grid, added to the ModernBERT tokenizer.Training: every sentence in a passage is scored with VADER and prefixed with itsown sentiment token. One sentence is then masked out. The model must reconstructit from the token it was given and the text on both sides — so it learns towrite a sentence that hits a requested sentiment *and* fits its neighbours.Generation reverses this. Prefix each sentence with its current sentiment, givethe target sentence the sentiment you *want*, mask its words, and fill the maskswith beam search. Because the generator is a bidirectional encoder rather than adecoder, every token it writes is conditioned on the text before **and** after —which is what lets it replace a sentence mid-passage.## ExamplesRewriting sentence `[3]` at **−0.8**. The model picks up "tunnel" from thepreceding sentence:> Once upon a time, there was a little boy named Timmy. One day, Timmy went to a> park with his mommy. At the park, there was a big tunnel that Timmy wanted to> explore. **~~Timmy's mommy said he could choose whether or not to go through> the tunnel.~~ → But Timmy's mommy said no because it was too dangerous.**> Timmy was brave and decided to go through the tunnel. As Timmy crawled through> the tunnel, he felt mighty and strong. When he came out the other side, he was> so happy and proud of himself. From that day on, Timmy loved going on> adventures and choosing to be brave.Rewriting sentence `[2]` of a restaurant review at **+0.8**. The model carriesthe business name "Lotus 2" in from context:> I ordered delivery this evening and I must say that I was pleasantly surprised> at the level of customer service on the phone and at my door. I usually get my> Chinese take out from best wok 2 and they pale in comparison to lotus 2.> **~~I ordered the exact same things that I usually order from best wok and> everything tasted better and was of better quality and was even a little less> expensive.~~ → Lotus 2 are very friendly and always make sure that I get the> best quality of food and I get a lot of value for my money.** I am so happy> that I've found a new Chinese take out. And they deliver! Of course its not> P.F. Changs. But its well worth what you pay.## Use cases- **Writing assistant for fiction.** Adjust the emotional arc of a draft onesentence at a time — darken a turning point, soften an ending — withoutrewriting the surrounding prose.- **Review and copy editing.** Retune the tone of a testimonial, productdescription or release note while keeping the concrete details intact.- **Data augmentation.** Generate sentiment-varied paraphrases of a corpus atknown target values: balance a skewed sentiment dataset, or produce minimalpairs that differ in sentiment but share context.- **Counterfactual and robustness testing.** Probe a downstream classifier withinputs where exactly one sentence's sentiment moved, holding everything elsefixed.- **Controllable-generation research.** A non-autoregressive baseline forcontinuous attribute control, and a testbed for how far a control signal canbe pushed at inference time.## UsageNo install needed — the inference code ships in this repo.```bashgit clone https://huggingface.co/shawhed/SenseShift-large7 unmodified linesshifter = SenseShift.from_pretrained("SenseShift-large")text = ("At the park, there was a big tunnel that Timmy wanted to explore. ""Timmy's mommy said he could choose whether or not to go through the tunnel. ""Timmy was brave and decided to go through the tunnel.")# Rewrite a sentence at a target sentimentout = shifter.generate(text, generation_mode="rewrite", sentence_index=1, sentiment=-0.8)print(out.sentence)print(out.text)# Write a new sentence and splice it in after sentence 2out = shifter.generate(text, generation_mode="add", sentence_index=2, sentiment=0.9)print(out.text)```Requires `torch`, `transformers`, `huggingface-hub`, `nltk`. The VADER lexicondownloads itself on first use.### `generate` arguments| Argument | Default | Meaning || --- | --- | --- || `text` | — | The passage to edit. || `generation_mode` | `"rewrite"` | `"rewrite"` replaces the sentence at `sentence_index`; `"add"` inserts a new sentence after it. || `sentiment` | `None` | `None` keeps the current sentiment; `"random"` draws from the grid; a number in `[-1, 1]` is snapped to the nearest 0.1. || `sentence_index` | `None` | Which sentence to act on. Defaults to a random sentence (`rewrite`) or the last one (`add`). Negative indices count from the end. || `num_masks` | `None` | Mask slots given to the model, i.e. roughly how long the new sentence is. Defaults to the replaced sentence's word count, or 12 for `add`. || `seed` | `None` | Seeds the random index / sentiment draws. |Decoding parameters — leave any at `None` to use the model's defaults:| Argument | Default | Meaning || --- | --- | --- || `beam_size` | `2` | Hypotheses kept alive. Higher is slower and usually more fluent. `num_beams` works as an alias. || `top_k` | `40` | Candidate tokens considered per masked position. || `temperature` | `0.8` | Below 1.0 is more conservative, above 1.0 more varied. || `alpha` | `0.7` | Length-normalisation exponent; higher tolerates longer output. || `gamma` | `0.05` | Diversity penalty on beams reusing the same token. || `max_iters` | `30` | Cap on mask-filling steps. || `min_words` | `3` | Tokens filled before the model may stop at punctuation. Raise to avoid very short rewrites. |```pythonout = shifter.generate(text, sentence_index=1, sentiment=-0.8, beam_size=8, top_k=60, temperature=0.9)````generate` returns a `SenseShiftOutput` with `.text` (the edited passage),`.sentence` (what was written), `.original_sentence`, `.target_sentiment`,`.achieved_sentiment` (VADER of the result) and `.beams`. `str(out)` gives thepassage.## Training dataTinyStories-style short children's stories, labelled per sentence with VADER.Despite the narrow training domain it transfers to other English prose — thereview example above is out-of-domain.Negative sentiment is under-represented in that corpus, so the negative half ofthe range is a looser steer than the positive half, and the extremes `±1.0` areeffectively untrained. **Use targets in −0.9 … +0.9**, and read`out.achieved_sentiment` if you need a specific value.## CitationAccepted to EMNLP 2026. A preprint and BibTeX entry will be linked here oncethey are public.
120 unmodified lines12112212312412512612712 unmodified lines1401411421431441451461473 unmodified lines151152153154155156157158159160120 unmodified linessentence_index: Optional[int] = None,num_masks: Optional[int] = None,seed: Optional[int] = None,**overrides,) -> SenseShiftOutput:"""Rewrite one sentence, or add a new one, at a controlled sentiment.12 unmodified lineslength of what it writes. Defaults to the replaced sentence'sword count (``"rewrite"``) or ``add_num_masks`` (``"add"``).seed: Seed for the sentence/sentiment draws, for reproducibility.**overrides: Per-call decoding overrides — ``top_k``, ``beam_size``,``max_iters``, ``alpha``, ``gamma``, ``temperature``, ``min_words``.Returns:A :class:`SenseShiftOutput`; ``str(out)`` is the edited passage.3 unmodified linesf"generation_mode must be 'rewrite' or 'add', got {generation_mode!r}")params = {**self.generation_defaults, **overrides}unknown = set(overrides) - set(DEFAULT_GENERATION)if unknown:raise TypeError(f"Unknown generation option(s): {', '.join(sorted(unknown))}")rng = _random.Random(seed) if seed is not None else _random120 unmodified lines12112212312412512612712812913013113213313412 unmodified lines1471481491501511521531541551561571581591601611621631641653 unmodified lines169170171172173174175176177178179180181182183184185186187188189190191120 unmodified linessentence_index: Optional[int] = None,num_masks: Optional[int] = None,seed: Optional[int] = None,beam_size: Optional[int] = None,top_k: Optional[int] = None,temperature: Optional[float] = None,alpha: Optional[float] = None,gamma: Optional[float] = None,max_iters: Optional[int] = None,min_words: Optional[int] = None,num_beams: Optional[int] = None,) -> SenseShiftOutput:"""Rewrite one sentence, or add a new one, at a controlled sentiment.12 unmodified lineslength of what it writes. Defaults to the replaced sentence'sword count (``"rewrite"``) or ``add_num_masks`` (``"add"``).seed: Seed for the sentence/sentiment draws, for reproducibility.beam_size: Hypotheses kept alive during decoding. Higher is slowerand usually more fluent. ``num_beams`` is accepted as an alias.top_k: Candidate tokens considered at each masked position.temperature: Softmax temperature. Below 1.0 is more conservative,above 1.0 more varied.alpha: Length-normalisation exponent; higher tolerates longer output.gamma: Diversity penalty on beams reusing the same token.max_iters: Cap on mask-filling steps.min_words: Tokens that must be filled before the model may stop atterminal punctuation. Raise it to prevent very short rewrites.Any decoding argument left as ``None`` falls back to the model'sdefaults from ``senseshift_config.json``.Returns:A :class:`SenseShiftOutput`; ``str(out)`` is the edited passage.3 unmodified linesf"generation_mode must be 'rewrite' or 'add', got {generation_mode!r}")if num_beams is not None:if beam_size is not None and beam_size != num_beams:raise TypeError("Pass either beam_size or num_beams, not both.")beam_size = num_beamsoverrides = {"beam_size": beam_size, "top_k": top_k, "temperature": temperature,"alpha": alpha, "gamma": gamma, "max_iters": max_iters,"min_words": min_words,}params = {**self.generation_defaults,**{k: v for k, v in overrides.items() if v is not None}}if params["beam_size"] < 1 or params["top_k"] < 1:raise ValueError("beam_size and top_k must be >= 1.")if params["temperature"] <= 0:raise ValueError("temperature must be > 0.")rng = _random.Random(seed) if seed is not None else _random
README.md+113-151
senseshift/__pycache__/__init__.cpython-311.pycAdded
senseshift/__pycache__/decoding.cpython-311.pycAdded
senseshift/__pycache__/masking.cpython-311.pycAdded
senseshift/__pycache__/pipeline.cpython-311.pycAdded
senseshift/__pycache__/text_utils.cpython-311.pycAdded
senseshift/pipeline.py+38-7